ESLint不允许进入

use*_*203 20 javascript for-in-loop eslint

我有一个对象

currentValues= {hey:1212, git:1212, nmo:12121}
Run Code Online (Sandbox Code Playgroud)

我用这样的:

for (const key in currentValues) {
    if (Object.prototype.hasOwnProperty.call(currentValues, key)) {
        yield put(setCurrentValue(key, currentValues[key]));
    }
}
Run Code Online (Sandbox Code Playgroud)

ESLint向我显示了一个错误:

ESLint:for..in循环遍历整个原型链,这几乎不是你想要的.使用Object.{keys,values,entries},并迭代生成的数组.(没有限制的语法

我该如何编辑我的代码?

ris*_*uri 31

它说,

使用Object.{keys,values,entries},并迭代生成的数组.

因此,您可以执行类似这样的操作,将对象键作为数组,然后循环键以进行必要的更改.

currentValues= {hey:1212, git:1212, nmo:12121}

Object.keys(currentValues).forEach(function(key) {
  yield put(setCurrentValue(key, currentValues[key]));
})
Run Code Online (Sandbox Code Playgroud)

  • 是的,但我不明白为什么?这可能真的是一个问题吗? (3认同)
  • 这怎么能比普通的旧式“for in”更直观或更简短呢? (3认同)
  • @Jonny `for..in` 将按照 ESLint 消息的解释循环遍历整个原型链,因此您最终会在循环中得到意外的项目。为了避免这种情况,人们会在“for..in”循环中添加一个“if (Object.prototype.hasOwnProperty.call...)”(请参阅​​OP代码示例)。使用“Object.keys”消除了在“for..in”中使用“if”的需要,它比使用“for..in”更加干净和直接。 (3认同)
  • 'yield' 表达式只允许出现在生成器主体中 (3认同)

use*_*203 6

我使用了以下内容:

const keys = Object.keys(currentValues);
const values = Object.values(currentValues);
for (let i = 0; i < keys.length; i += 1) {
    yield put(setCurrentValue(keys[i], values[i]));
}
Run Code Online (Sandbox Code Playgroud)

这是正确的,没有ESLint错误.


小智 5

我会通过以下方式重构来做到这一点。

const currentValues = { hey: 1212, git: 1212, nmo: 12121 };

Object.keys(currentValues).forEach((e) => console.log(`${e} : ${currentValues[e]}`));
Run Code Online (Sandbox Code Playgroud)

结果:

嘿:1212 git:1212 nmo:12121

Object.values(currentValues).forEach((e) => console.log(`Values: ${e}`));
Run Code Online (Sandbox Code Playgroud)

结果:

(2)数值:1212 数值:12121

Object.entries(currentValues).forEach((e) => console.log(`${e[0]} : ${e[1]}`));
Run Code Online (Sandbox Code Playgroud)

结果:

嘿:1212 git:1212 nmo:12121


小智 0

使用for...in将迭代所有属性,包括来自对象原型的属性。我不知道你为什么这样做Object.prototype.hasOwnProperty.call(currentValues, key) 而不只是: currentValues.hasOwnProperty(key)。我认为这应该让 ESLint 意识到您只过滤自己的属性。

不过,我建议使用for (const key of Object.keys()),它更具语义性。