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

javascript - Use for loop for array provide errror - Stack Overflow

programmeradmin3浏览0评论

I use the following code that works as expected, while using a ESLINT i got error

ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. (no-restricted-syntax)

This is the code

for (const subscription of resp.data.subscriptions) {
  if (subscription.url) {
    return subscription.url;
  }
}

The code is simply

  • get an array of data from other function
  • loop on each array item
  • when the first array instance have url take it and return

Is there a way to write it better to avoid the eslint issue ?

I use the following code that works as expected, while using a ESLINT i got error

ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. (no-restricted-syntax)

This is the code

for (const subscription of resp.data.subscriptions) {
  if (subscription.url) {
    return subscription.url;
  }
}

The code is simply

  • get an array of data from other function
  • loop on each array item
  • when the first array instance have url take it and return

Is there a way to write it better to avoid the eslint issue ?

Share Improve this question asked Aug 4, 2020 at 6:41 Beno OdrBeno Odr 1,2733 gold badges17 silver badges30 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 12

There is a debate about for...of usage here and its eventual restriction

for(let i = 0; i < array.length; i ++) { ... } is antiquated syntax, and while I know everyone understands what it means, we should be leaving it behind.

array.map has functional connotations and we shouldn't be producing side effects in the closure.

array.forEach is an option, but I personally don't like it for this sort of imperative work.

So I think the ForOfStatement should be removed from the restricted syntax for the above reasons - anyone with any conflicting viewpoints? Do we know what the original justification is?

for..of is more expensive than forEach, check this out

I have no opinions, you could just remove the eslint rule

You can use a .filter to solve this:

var arrObjWithURL = resp.data.subscriptions.filter(function(item) {
    return item.url;
});

if (arrObjWithURL.length > 0) {
    return arrObjWithURL[0];
}

You can also use .find:

return resp.data.subscriptions.find(function(item) {
    return item.url;
});

... or this to continue if there is no URL found:

const objWithUrl = resp.data.subscriptions.find(function(item) {
    return item.url;
});

if (objWithUrl !== undefined) {
    return objWithUrl;
}

demo on jsfiddle

发布评论

评论列表(0)

  1. 暂无评论