Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
173 views
Welcome To Ask or Share your Answers For Others

1 Answer

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...