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

Javascript arrow function instead of for...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;
            }
        } 

最后一个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) || {}

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);