[英]why forEach() doesn't work in this object loop?
Why forEach doesn't work for the following? 为什么forEach在以下项目中不起作用? 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
在块体中,必须使用显式的return语句
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) } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.