[英]Javascript arrow function instead of for…of
如何使用箭头函数缩短语法的...?
this.id = 1;
let products: Product[] = [
{
"id": 1,
"name": "Bycicle"
},
{
"id": 2,
"name": "iPhoneX"
}
];
for (let p of products) {
if (p.id == this.id) {
this.product = p;
break;
}
}
可以将最后一个代码块写成一行吗? 我尝试了这个,但是看起来太错误了:
this.product = products.filter(p => p.id == this.id)[0];
我正在寻找.NET中的.FirstOrDefault之类的东西
this.product = products.find(p => p.id === this.id)
要获得与firstOrDefault
等效的结果,可以短路结果
this.product = products.find(p => p.id === this.id) || {}
find
应该做的
this.product = products.find(p => p.id === this.id);
演示
let id =1; var products = [ { "id": 1, "name": "Bycicle" }, { "id": 2, "name": "iPhoneX" } ]; let product = products.find(p => p.id === id); console.log(product);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.