下午好!
我找到了此代码,我很惊讶键盘上的"backspace"
将其转换为NUMBER
:
let x = null;
x = prompt("Write something: ", "");
if((x == null) || (x == "")) {
alert("Nothing was written");
} else {
if("NaN" == 1*x+"") {
alert("A string was written");
} else {
alert("A number was written");
}
}
为什么?而且-如何治疗呢?
然后,我的第二个问题:
上面写着let x = null
。我可以改写let x = ""
吗?还是只有let x
?
非常感谢!
答案 0 :(得分:-1)
let x;
x = prompt("Write something: ", "");
console.log("NaN" == 1); //this will always be false
console.log(1 * x); //x is multiplied by 1 if it is a number
//if x is a letter prints 'NaN'
//if x is null prints 0 because x is converted to a number and when we do this conversion null becomes 0
//if x is empty space also prints zero because when javascript converts " " to a number the result is 0
console.log(x + ""); //x is converted to a string if it is a number, but this essentially just prints the value of x
console.log("NaN" == 1 * x + "");
//because of the order of operations, our first step is to multiply 1 by x
//if x is a space, the result is 0 | 1 * " " = 0
//if x is null, the result is 0 | 1 * null = 0
//if x is a letter, returns NaN | 1 * A = NaN
//if x is a number, returns the number | 1 * 2 = 2
//next we add "" to whatever value we got in the first step
//if the current value of x is 0 we are left with "NaN" == 0, which is false
//if the current value of x is a letter, we are left with "NaN" == "NaN", which is true
//if the current value of x is a number, we are left with "NaN" == *a number* which is false
if ((x === null) || ( x.trim() === "")) { //check if x is empty space
alert("Nothing was written");
} else {
if (Number(x) === "NaN") { //will return true if x contains letters
alert(Number(x));
} else {
alert(Number(x)); //we end up here if x is a number
}
}
好的,以上内容可以回答您的第一个问题。至于第二个,初始化x并不重要,因为在下一行中给它分配了一个值。该值是一个字符串,一旦开始使用数学运算,JavaScript只会尝试将其转换为数字。
答案 1 :(得分:-2)
在JS中,“” == 0等于true,因此在尝试执行+“”时最终显示为+ 0