gpt4 book ai didi

Javascript 箭头函数代替 for...of

转载 作者:行者123 更新时间:2023-11-28 14:46:22 25 4
gpt4 key购买 nike

如何使用箭头函数缩短 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;
}
}

最后一个 block 可以用一行写吗?我尝试过,但看起来很错误:

this.product = products.filter(p => p.id == this.id)[0];

我正在 .NET 中寻找类似 .FirstOrDefault 的内容

最佳答案

使用Array#find

this.product = products.find(p => p.id === this.id)

要获得与 firstOrDefault 等效的结果,您可以将结果短路

this.product = products.find(p => p.id === this.id) || {}

关于Javascript 箭头函数代替 for...of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46254377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com