如何使用箭头函数缩短语法?
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
这样的东西答案 0 :(得分:2)
this.product = products.find(p => p.id === this.id)
要获得等效于firstOrDefault
,您可以将结果短路
this.product = products.find(p => p.id === this.id) || {}
答案 1 :(得分:2)
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);
&#13;