在“你不懂 JS”一书中,我有一个关于 isNaN polyfills 的问题
In the book 'You Don't Know JS', I have a question about isNaN polyfills
在 Kyle Simson 的书中 You Don't Know JS
,
You can also implement polyfills more simply by applying uniqueness that NaN does not equal to itself.
NaN is the only value in all languages of the world "any value other than self is always equal to you."
提出函数isNaN的polyfill如下
// polyfill NaN
if (!Number.isNaN) {
Number.isNaN = function(n) {
return n !== n;
};
}
然而,代码n! == n
总是被强制false
吗? (其实我把函数简单化了执行也是一样的)
所以我不明白代码的意思。
如果你能解释一下,我将不胜感激。
NaN
是 Javascript 中的 only 值,当与 ===
与自身进行比较时,会产生 false
(或者,等效地,当与自身与 !==
、returns true
进行比较时。任何其他值,当使用 ===
与自身进行检查时,将 return true
.
NaN !== NaN // true
const obj = {};
obj !== obj // false
0 !== 0 // false
'foo' !== 'foo' // false
// etc, everything else other than NaN
// will produce: // false
所以
return n !== n;
是 n
是否为 NaN
的可靠检查。
在 Kyle Simson 的书中 You Don't Know JS
,
You can also implement polyfills more simply by applying uniqueness that NaN does not equal to itself. NaN is the only value in all languages of the world "any value other than self is always equal to you."
提出函数isNaN的polyfill如下
// polyfill NaN
if (!Number.isNaN) {
Number.isNaN = function(n) {
return n !== n;
};
}
然而,代码n! == n
总是被强制false
吗? (其实我把函数简单化了执行也是一样的)
所以我不明白代码的意思。
如果你能解释一下,我将不胜感激。
NaN
是 Javascript 中的 only 值,当与 ===
与自身进行比较时,会产生 false
(或者,等效地,当与自身与 !==
、returns true
进行比较时。任何其他值,当使用 ===
与自身进行检查时,将 return true
.
NaN !== NaN // true
const obj = {};
obj !== obj // false
0 !== 0 // false
'foo' !== 'foo' // false
// etc, everything else other than NaN
// will produce: // false
所以
return n !== n;
是 n
是否为 NaN
的可靠检查。