admin管理员组文章数量:1426002
I am generating an array of objects based on the quantity of items in another array. Pretty simple, I'm just doing the following, which works fine.
for(let i in myArray){
newArray.push({
var1: someFunctionValue(),
var2: anotherFunctionValue()
});
}
However, because "i" is not being used, React (ESLint?) gives me the warning 'i' is assigned a value but never used - no-unused-vars.
Is there a better way I should be doing this? I don't really see a way to achieve what I want without producing this error.
I am generating an array of objects based on the quantity of items in another array. Pretty simple, I'm just doing the following, which works fine.
for(let i in myArray){
newArray.push({
var1: someFunctionValue(),
var2: anotherFunctionValue()
});
}
However, because "i" is not being used, React (ESLint?) gives me the warning 'i' is assigned a value but never used - no-unused-vars.
Is there a better way I should be doing this? I don't really see a way to achieve what I want without producing this error.
Share Improve this question asked Jul 22, 2018 at 19:14 AlexAlex 1,4031 gold badge19 silver badges31 bronze badges3 Answers
Reset to default 5You're using a for-in loop over an array, without using the enumerable keys (indices). You should use Array#forEach
instead, and since it accepts a callback, you can just omit any arguments:
myArray.forEach(() => { // No callback args
newArray.push({
var1: someFunctionValue(),
var2: anotherFunctionValue()
});
});
Also, now that I'm reading your variable names, it seems you're trying to do a mapping operation, as in for every element in myArray
, you want a new one in newArray
associated with each index. If that's the case, the better method is to Array#map
your myArray
:
const newArray = myArray.map(() => ({
var1: someFunctionValue(),
var2: anotherFunctionValue(),
}));
There's no need for any intermediacy and it's concise.
You could use forEach
instead which doesn't need a variable:
myArray.forEach(() => {
newArray.push({
var1: someFunctionValue(),
var2: anotherFunctionValue()
});
});
Based on this answer. You can also try declaring the variable outside the loop.
For my use case I needed a break
statement so forEach()
wouldn't work for me.
let i = null;
for(i in myArray){
if (i==='fooBar') {
break;
}
else {
newArray.push({
var1: someFunctionValue(i),
var2: anotherFunctionValue()
});
}
}
本文标签: javascriptAvoid React quotnounusedvarsquot error with loopStack Overflow
版权声明:本文标题:javascript - Avoid React "no-unused-vars" error with loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745390583a2656578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论