数组原型是只读的,不应添加属性no-extend-native

AH.*_*and 5 javascript reactjs eslint

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

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

  return index === -1;
};
Run Code Online (Sandbox Code Playgroud)

并且可以相当有效地检查给定的针是否处于反应状态。但是ESlint一直说:

Array prototype is read only, properties should not be added  no-extend-native
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:我的代码有什么问题?

Jus*_*ode 16

来自 EsLint 文档:

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

例如,我们在这里覆盖了一个内置方法,该方法将影响所有对象,甚至其他内置方法。

// 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"
}
Run Code Online (Sandbox Code Playgroud)

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

因此,在您的情况下,此示例将应用于数组。

// 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"
}
Run Code Online (Sandbox Code Playgroud)

变通办法


您可以添加此行以忽略警告。

/*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]*/ to ignore that warning.
Run Code Online (Sandbox Code Playgroud)

参考:https : //eslint.org/docs/rules/no-extend-native


Ash*_*far 15

这是因为 esLint 将其突变为原生 protoTypes 链。您可以// eslint-disable-next-line no-extend-native在该行上方添加它应该没问题。