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

新手上路,请多包涵

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

 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

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

原文由 AH.Pooladvand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 824
2 个回答

来自 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"
}

简而言之, Array.prototype.inState 将扩展 array.prototype 因此无论何时你想使用一个数组,instate 函数也将被添加到该数组。

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

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

  return index === -1;
};

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

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

解决方法


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

 /*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]*/ to ignore that warning.

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

原文由 Just code 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Ashif Zafar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题