Avoid no-sequences inside map function

爱⌒轻易说出口 提交于 2021-01-29 15:02:11

问题


I have a array which I want to loop through so I use the map prototype. Inside the callbackfn of each element I want to run several expressions.

const test = [{ name: "foo", value: "1" }, { name: "bar", value: "2" }, { name: "x", value: "3" }]
  let found = false;
  test.map(name => (
    console.log(name.name),
    console.log(name.value),
    found = true
  ));

I've separated each expression with a ,. Whilst this runs correctly and produces the correct results I can see my eslint saying Unexpected use of comma operator no-sequences

How am I meant to put multiple expressions inside the map function?


回答1:


How am I meant to put multiple expressions inside the map function?

Use curly braces:

test.map(name => {
   console.log(name.name)
   console.log(name.value)
   found = true
});

Though map doesn't look the right choice for this as pointed out others - looks like you should use filter, but the same rules apply for multiple statements.

Normal brackets are a shorthand for 'implied return', where you can omit the {} and the return keyword if your function only contains one expression. In fact, you can usually omit the brackets too!

So these are equivalent:

test.filter(name => {
    let found = false
    if(name==='sarah'){
       found = true
    }
    return found 
}

test.filter(name => name === 'sarah')



回答2:


For completeness from my comment then: use forEach and things other people have mentioned.

const test = [{ name: "foo", value: "1" }, { name: "bar", value: "2" }, { name: "x", value: "3" }]
  let found = false;
  test.forEach(name => {
    console.log(name.name);
    console.log(name.value);
    found = true;
  });



回答3:


You have a syntax error in your code, since the correct syntax for an arrow function with multiple lines of code is:

(params) => {
  // Your code here with semicolon at line end
}

Note the use of curly braces instead of parentheses and the semicolon instead of comma at line end.

Also, since you are seeking for some value inside and don't care about it position, you can use Array.some() instead. It will be more efficient since it stops on first result:

let found = test.some((name) => {
  if (your condition here) {
    return true;
  } else {
    return false;
  }
});


来源:https://stackoverflow.com/questions/60615901/avoid-no-sequences-inside-map-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!