简体   繁体   中英

why forEach() doesn't work in this object loop?

Why forEach doesn't work for the following? I tried it a few times and it always return "unexpected token".

// for loop
for(item in items){
        if (items[item].id===idNum){
            console.log(items[item]);
        }
    }

// the for loop works. 

// forEach()

items.forEach(item=>if(item.id===idNum){console.log(item)})
// this returned error message "unexpected token"

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement

reference :- Arrow function body

Because this syntax is not correct.

items.forEach(item=>if(item.id===idNum){console.log(item)})

You need to use {} here

items.forEach(item=>{
if(item.id===idNum){console.log(item)}
})

You have to use brackets for function body:

 let items = [ {id:1}, {id:2} ]; let idNum = 2; items.forEach(item => { if (item.id === idNum) { console.log(item) } }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM