【发布时间】:2019-09-28 05:52:53
【问题描述】:
所以首先这不是我面临的问题。当我遇到.indexOf and .includes的Array原型方法时,我正在浏览一些Javascript的博客。因此,如果一个数组有NaN 作为值,那么indexOf 可能无法计算出来,我只能使用.includes。但我的问题是,既然includes 的浏览器兼容性实际上不包括IE,那么检测NaN 检查的替代方法应该是什么?我想通过引用this来构建一个polyfill
if (Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
enumerable: false,
value: function(obj) {
var newArr = this.filter(function(el) {
return el == obj;
});
return newArr.length > 0;
}
});
}
var arr = [NaN];
console.log(arr.includes(NaN));
但不幸的是,它也返回 false。那么我还有什么其他选择?还是我错过了什么?
【问题讨论】:
-
你可以使用
arr.findIndex()找到NaN的索引 -
includes()的 polyfill 可以是 found on MDN。 -
@VLAZ 我一开始也是这么想的,但事实并非如此!请参阅 ecma-international.org/ecma-262/7.0/#sec-samevaluezero ,
NaN是一个例外。If x is NaN and y is NaN, return true. -
@CertainPerformance 是的,看来我在这里错了。出于某种原因,我认为我过去什至使用过
[NaN].includes(NaN)并获得了false。无论如何,MDN的实现应该是正确的 -
请注意,您的 polyfill 可能应该将
if (Array.prototype.includes) {更改为if (!Array.prototype.includes) {
标签: javascript arrays nan polyfills