Javascript typeof 和 IsNaN
Javascript typeof and IsNaN
在 Array.prototype.includes()
的 MDN polyfill 函数中,我找到了以下代码。
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
在上面的代码中
typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)
这让我很困惑。如果 typeof
变量是一个数字, isNaN
将始终为 false 对吗?那么整个条件什么时候会 return 为真?有人可以解释一下还是我理解错了?
在JavaScript中,NaN
的类型是number
。我猜这是因为它是数学运算的结果。
有关详细信息,请参阅 this question。
不是,如果typeof x === 'number'
,x
可以是NaN
,那么isNaN(x) && typeof x === 'number'
就会是true
。
虽然不知道为什么那个函数不使用 Number.isNaN(x) && Number.isNaN(y)
,因为它会明确检查值是否为 NaN
(而不是任何可以 NaN
的值转换为数字,如 isNaN
).
如果 2 个元素是 NaN
,此代码将 return true
,但如果两者都不是数字,则 false
。
如您所见,第一个示例 returns true
都是 isNaN()
而不管它们的类型 - 这使得 a
等于 b
。第二次在使用 isNaN()
:
之前检查两者是否都是数字
const checkEq1 = (x, y) => isNaN(x) && isNaN(y)
console.log(checkEq1(NaN, NaN)); // true
console.log(checkEq1('a', 'b')); // true - error
const checkEq2 = (x, y) => typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)
console.log(checkEq2(NaN, NaN)); // true
console.log(checkEq2('a', 'b')); // false
在 Array.prototype.includes()
的 MDN polyfill 函数中,我找到了以下代码。
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
在上面的代码中
typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)
这让我很困惑。如果 typeof
变量是一个数字, isNaN
将始终为 false 对吗?那么整个条件什么时候会 return 为真?有人可以解释一下还是我理解错了?
在JavaScript中,NaN
的类型是number
。我猜这是因为它是数学运算的结果。
有关详细信息,请参阅 this question。
不是,如果typeof x === 'number'
,x
可以是NaN
,那么isNaN(x) && typeof x === 'number'
就会是true
。
虽然不知道为什么那个函数不使用 Number.isNaN(x) && Number.isNaN(y)
,因为它会明确检查值是否为 NaN
(而不是任何可以 NaN
的值转换为数字,如 isNaN
).
如果 2 个元素是 NaN
,此代码将 return true
,但如果两者都不是数字,则 false
。
如您所见,第一个示例 returns true
都是 isNaN()
而不管它们的类型 - 这使得 a
等于 b
。第二次在使用 isNaN()
:
const checkEq1 = (x, y) => isNaN(x) && isNaN(y)
console.log(checkEq1(NaN, NaN)); // true
console.log(checkEq1('a', 'b')); // true - error
const checkEq2 = (x, y) => typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)
console.log(checkEq2(NaN, NaN)); // true
console.log(checkEq2('a', 'b')); // false