JS中的这段代码给了我一个弹出窗口,说"我认为null是一个数字",我觉得有点令人不安.我错过了什么?
if (isNaN(null)) {
alert("null is not a number");
} else {
alert("i think null is a number");
}Run Code Online (Sandbox Code Playgroud)
我正在使用Firefox 3.这是一个浏览器错误吗?
其他测试:
console.log(null == NaN); // false
console.log(isNaN("text")); // true
console.log(NaN == "text"); // falseRun Code Online (Sandbox Code Playgroud)
那么,问题似乎不是与NaN的精确比较?
编辑:现在问题已经得到解答,我已经清理了我的帖子,以便为存档提供更好的版本.然而,这使得一些评论甚至一些答案有点难以理解.不要责怪他们的作者.我改变的事情包括:
ES2020 introduced the nullish coalescing operator (??) which returns the right operand if the left operand is null or undefined. This functionality is similar to the logical OR operator (||). For example, the below expressions return the same results.
const a = undefined
const b = "B"
const orOperator = a || b
const nullishOperator = a ?? b
console.log({ orOperator, nullishOperator })
Run Code Online (Sandbox Code Playgroud)
result:
{
orOperator:"B",
nullishOperator:"B"
}
Run Code Online (Sandbox Code Playgroud)
So how is the nullish operator different …
我有一个代码,返回给我在bootstrap模式中的javascript平均函数的结果.但当其中一个输入空白时,他会返回NaN.我如何将NaN更改为0?
这是我的代码返回结果:
$(".average").click(function () {
var result = average();
$("#myModal .modal-body h2").text(result);
$("#myModal").modal();
});
Run Code Online (Sandbox Code Playgroud)