最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Avoid React "no-unused-vars" error with loop - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 5

You'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()
  });

}


}

发布评论

评论列表(0)

  1. 暂无评论