在Javascript中,为什么使用空格键;转化为;到我的代码中的一个数字?

在Javascript中,为什么使用空格键;转化为;到我的代码中的一个数字?,javascript,Javascript,下午好 我发现了这个代码,我很惊讶小键盘上的“backspace”会将它转换成一个数字: 设x=null; x=提示(“写点东西:”,“”); if((x==null)| |(x==“”){ 警报(“未写入任何内容”); }否则{ 如果(“NaN”==1*x+”){ 警报(“写入了字符串”); }否则{ 警报(“写了一个数字”); } }在JS中,“==0等于true,因此当尝试执行+”时,结果为+0 let x; x = prompt("Write something: ", ""); c

下午好

我发现了这个代码,我很惊讶小键盘上的
“backspace”
会将它转换成一个
数字:

设x=null;
x=提示(“写点东西:”,“”);
if((x==null)| |(x==“”){
警报(“未写入任何内容”);
}否则{
如果(“NaN”==1*x+”){
警报(“写入了字符串”);
}否则{
警报(“写了一个数字”);
}
}
在JS中,“==0等于true,因此当尝试执行+”时,结果为+0

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仅在您开始对其进行数学运算后才尝试将其转换为数字。

这应该是做什么的<代码>“NaN”==1*x+“
”还有,请回答我的第二个问题”-不要在一个问题中问多个不相关的问题,或者只问一个不相关的问题。这使得回答/关闭重复项变得更加困难。您可以将x设置为“81278127398127312UIHKHDKJAHDIQWEYQIUYQWKJEHQWKJEKJEH”,这并不重要。您是否尝试过调试代码并在提示后看到x的值?谁对本页上的所有答案投了反对票?太好了!这是唯一一个不会将点击键盘上的空格键(英文:空格?空白?空白?)转换为数字的代码。还有,请问,有没有可能提醒我自己的文本而不是“NaN”?因为这个词永远不会被非程序员所理解,而我的想法会走向未来。非常感谢您的时间:-)@Joan要更改警报文本,您只需将
Number(x)==“NaN”
之后的
Number(x)
替换为您希望显示的文本。是的,在英语中只是空格。@Katie.Sun谢谢!不幸的是,代码工作起来很奇怪:我只更改了
警报(“输入了一个数字”+x+)在最后一个
else
中,由于我在两个警报中都输入了短语
一个数字!不管我输入的是数字还是字符串。一个小小的解释:在未来,学习更多的Javascript,我想为我残疾的侄女写一些简单的任务,因此我需要知道如何编写非常可压缩的脚本alerts@Katie.Sun好极了,我已经解决了:-)我只是用你的
(x.trim()===”)
替换了我的
(x==”)
,代码运行得很好。再见!那无关紧要。问题中的代码从不将空格与零进行比较。