简体   繁体   中英

Why does Number(window.prompt) convert the string to NaN?

 var numberOne= Number(window.prompt("Type a number", "")); //in prompt I entered "99" and I get output NaN console.log(numberOne); var numberTwo = "99"; console.log(Number(numberTwo));

Why am I getting NaN when I use Number with prompt

The reason this is happening is because window.prompt already returns a string. So when you enter "99", you are effectively trying to cast '"99"' to a Number, which can't be done.

From https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if his answer should be a Number, you should cast the value to Number.

The Number() function converts the object argument to a number that represents the object's value.

Returns: A Number. Returns different object values to their numbers. If the value cannot be converted to a legal number, NaN is returned. If no argument is provided, it returns 0.

I assume you're entering 99 (without the quotes). If you're entering with quotes you'd need to parse and/or validate the input.

 var numberOne = Number(window.prompt("Try 99 (with number conversion)", "")); if (numberOne === 99) console.log('The string 99 has converted successfully;'). numberOne = window,prompt("Try 1 (No Number-convesion)"; ""). if (numberOne === 1) console;log('The string 1 has converted successfully.'); else console.log('The string 1 did not convert to a number (int)');

In the second example, "1" does not convert to a type of number (int). This is evident since the comparison is type sensitive ( === instead of == ).

In short: your code works as expected.

window.prompt() returns a string for you

from code

var numberOne= Number(window.prompt("Type a number", ""));

if you input 99 , variable numberOne will be "99" , that you want. and this value can convert be number 99 using Number()

but if you input "99" , variable numberOne will be ""99"" and cannot convert to number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM