什么是NaN?以及如何检查值是否为NaN?
NaN
表示“非数字”是 JS 中的一个值,该值是将数字转换或执行为非数字值的运算结果,因此结果为NaN
。
let a; console.log(parseInt('abc')); // NaN console.log(parseInt(null)); // NaN console.log(parseInt(undefined)); // NaN console.log(parseInt(++a)); // NaN console.log(parseInt({} * 10)); // NaN console.log(parseInt('abc' - 2)); // NaN console.log(parseInt(0 / 0)); // NaN console.log(parseInt('10a' * 10)); // NaN
JS 有一个内置的isNaN
方法,用于测试值是否为 isNaN 值,但是这个函数有一个奇怪的行为。
console.log(isNaN()); // true console.log(isNaN(undefined)); // true console.log(isNaN({})); // true console.log(isNaN(String('a'))); // true console.log(isNaN(() => { })); // true
所有这些console.log
语句都返回true
,即使我们传递的值不是NaN
。
在ES6
中,建议使用Number.isNaN
方法,因为它确实会检查该值(如果确实是NaN
),或者我们可以使自己的辅助函数检查此问题,因为在 JS 中,NaN是唯一的值,它不等于自己。
function checkIfNaN(value) { return value !== value; }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 什么是NaN?以及如何检查值是否为NaN?
码云笔记 » 什么是NaN?以及如何检查值是否为NaN?