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)
我使用了以下内容:
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()),它更具语义性。
| 归档时间: |
|
| 查看次数: |
24370 次 |
| 最近记录: |