Javascript 阵列原型是只读的,不应添加属性。无扩展本机

Javascript 阵列原型是只读的,不应添加属性。无扩展本机,javascript,reactjs,eslint,Javascript,Reactjs,Eslint,所以基本上我有这个代码: Array.prototype.inState = function (needle, haystack) { let index = this.findIndex(value => value[needle] === haystack); return index === -1; }; 它的工作原理足以检查给定的针是否处于反应状态。但ESlint一直说: Array prototype is read only, properties should

所以基本上我有这个代码:

Array.prototype.inState = function (needle, haystack) {
  let index = this.findIndex(value => value[needle] === haystack);

  return index === -1;
};
它的工作原理足以检查给定的针是否处于反应状态。但ESlint一直说:

Array prototype is read only, properties should not be added  no-extend-native
所以我的问题是:我的代码怎么了?

来自EsLint文档:

在JavaScript中,您可以扩展任何对象,包括内置或 “本机”对象。有时人们会改变这些本地人的行为 对象的方式打破了其他方面对它们的假设 部分代码

例如,这里我们重写一个内置方法,该方法将 影响所有对象,甚至其他内置对象

简而言之,
Array.prototype.inState
将扩展
Array.prototype
,因此,每当您想要使用数组时,inState函数也将添加到该数组中

因此,在您的例子中,这个示例将应用于数组

Array.prototype.inState=函数(针、草垛){
让index=this.findIndex(value=>value[pinder]==haystack);
收益指数==-1;
};
//循环使用一些用户标识
var users=[{“123”:“Stan”},{“456”:“David”}];
//不是你所期望的
for(用户中的变量id){
console.log(用户[id]);/“123”、“456”、“额外”

}
这是因为esLint使其变异为本机原型链。
您可以在行上方添加
//eslint disable next line no extend native
,这样就可以了。

@AH.Pooladvand这将是一个很好的转换
// seems harmless
Object.prototype.extra = 55;

// loop through some userIds
var users = {
    "123": "Stan",
    "456": "David"
};

// not what you'd expect
for (var id in users) {
    console.log(id); // "123", "456", "extra"
}