문제

I've just started my journey in programming and lately I've been learning how to use JavaScript at University. I am stuck on an exercise that I just cannot get my head around!

The question is: Write a digit test without using logical operators [hint: string operators].

So I need a test to see if there are any digits in a string. I've got as far as:

var x=prompt("Enter any characters"); (e.g. hello123)

var y="0123456789";

(I figured that the input should somehow compare to the y variable so I can get an answer)

That's all I got! Hopefully this shouldn't be too complicated. (Can't wait for that "Oh yeah.." moment!)

도움이 되었습니까?

해결책

I'm not quite sure what the exact bounds of your problem are, but you can use a regular expression to check for digits:

var x = prompt("Enter any characters");
if (x && x.match(/\d/)) {
    // there are digits in the string
}

or written a different way (either is valid):

var x = prompt("Enter any characters");
if (x && /\d/.test(x)) {
    // there are digits in the string
}

Note, this is also making sure that x is non-null and not empty before attempting to use it as a string because if the user cancels the prompt, it will return null.

\d in a regular expression means to match any digit

You can read about regular expressions in javascript here and about the string methods that use them here.


I'm still guessing as to what the real bounds of your problem is, but without regex and using only the functions you mention in your comments, you can do this:

var digits = "0123456789";

// get string from user
var str = prompt("Enter any characters");

// check each digit one at a time
if (str) {
    for (var i = 0; i < digits.length; i++) {
        // see if the next digit is in the string
        if (str.indexOf(digits.charAt(i)) {
            // found a digit
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top