Javascript ESLint没有';I don’我不允许你进来
我有一个目标Javascript ESLint没有';I don’我不允许你进来,javascript,eslint,for-in-loop,Javascript,Eslint,For In Loop,我有一个目标 currentValues= {hey:1212, git:1212, nmo:12121} 我用的是这样的: for (const key in currentValues) { if (Object.prototype.hasOwnProperty.call(currentValues, key)) { yield put(setCurrentValue(key, currentValues[key])); } } ESLint向我显示了一个
currentValues= {hey:1212, git:1212, nmo:12121}
我用的是这样的:
for (const key in currentValues) {
if (Object.prototype.hasOwnProperty.call(currentValues, key)) {
yield put(setCurrentValue(key, currentValues[key]));
}
}
ESLint向我显示了一个错误,该错误表示:
ESLint:for..in循环在整个原型链上迭代,这实际上从来都不是您想要的。使用对象{键、值、条目},并在生成的数组上迭代。(无限制语法)
我应该如何编辑我的代码?在中为…使用
将迭代所有属性,包括来自对象原型的属性。我不确定为什么要执行对象.prototype.hasOwnProperty.call(CurrentValue,key)
而不仅仅是:
currentValues.hasOwnProperty(键)
。
我认为这应该让ESLint意识到,您只是在过滤自己的属性
但是,我建议使用for(Object.keys()的const key)
,这更具语义。您只需执行以下操作即可获得对象中所有值的数组
var myValuesInArray = Object.values(currentValues);
上面说,
使用对象{键、值、条目},并在结果上迭代
数组
因此,您可以这样做,将对象键作为数组获取,然后循环遍历这些键以进行必要的更改。
currentValues={hey:1212,git:1212,nmo:12121}
Object.key(currentValues).forEach(函数(key){
收益率卖出(setCurrentValue(键,CurrentValue[键]);
})
我使用了以下方法:
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]));
}
const keys=Object.keys(当前值);
常量值=对象值(CurrentValue);
for(设i=0;i
这是正确的,没有ESLint错误。我知道它与上述类似,但这里有一个完整的示例:
const data = res.data;
const keys = Object.keys(data);
const values = Object.values(data);
for (let i = 0; i <= keys.length; i += 1) {
if (Object.prototype.hasOwnProperty.call(values, i)) {
this.rows.push({
name: values[i].name,
email: values[i].email,
address: values[i].address,
phone: values[i].phone,
role: values[i].role,
});
}
}
const data=res.data;
常量键=对象键(数据);
常量值=对象值(数据);
对于(让i=0;i试试这个:
Object.keys(currentValues).map(key => (yield put(setCurrentValue(key, currentValues[key]))));
我将通过以下方式进行重构
const currentValues = { hey: 1212, git: 1212, nmo: 12121 };
Object.keys(currentValues).forEach((e) => console.log(`${e} : ${currentValues[e]}`));
结果:
嘿:1212
吉特:1212
nmo:12121
Object.values(currentValues).forEach((e) => console.log(`Values: ${e}`));
结果:
(2) 价值:1212
价值:12121
Object.entries(currentValues).forEach((e) => console.log(`${e[0]} : ${e[1]}`));
结果:
嘿:1212
吉特:1212
nmo:12121如果您只需要键,请尝试for(currentValues.keys()的const key)
如果您需要键和值,可以使用条目。@AndrewLi您是说Object.keys()
?如果是这样的话,这还是有问题的,因为在
中用for…迭代数组是不可取的。@Pointy我用for…of
?哦,对不起,继续:)但是,这个对象上没有.keys()
函数。我没有看到数组。使用hasOwnPrototype(…)对象中的更好。是的,但我不明白为什么?这可能真的是一个问题?对于in
,这怎么可能比普通的更直观或简短呢?如果使用对象.keys()
,则不需要hasOwnProperty
:
Object.values(currentValues).forEach((e) => console.log(`Values: ${e}`));