gpt4 book ai didi

javascript - 为什么这不返回 null?

转载 作者:数据小太阳 更新时间:2023-10-29 05:50:14 26 4
gpt4 key购买 nike

让我们运行这段 javascript 代码:

var value = parseInt("");
console.log(value != Number.NaN? value : null);

为什么这段代码在控制台输出Nan而不是null

如何更改我的代码以实际获取 null 对象?

我尝试将我的代码包装在这样的函数中:

function parseIntOrDefault(value, def){
var candidate = parseInt(value);
if(candidate != Number.NaN) return candidate; else return def;
}

console.log(parseIntOrDefault('', null));

但这表现相同。

这是一个说明我的问题的 jsFiddle:http://jsfiddle.net/stevebeauge/BRP94/

最佳答案

你应该使用

isNaN(value);

检查 NaN

因为:

console.log(NaN === NaN); // false!

NaN 不等于自身

这可能看起来很奇怪,但如果您考虑 NaN 的性质,它是有道理的。

假设您有这段代码:

var a, b, c;
// a = 0;oops a is still undefined so we'll get NaN if we do an operation with it
b = 5;
c = 6
if (a + b === a + c) {
console.log("math error?");
}

你不想得出 5 === 6 的表面结论。

关于javascript - 为什么这不返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com