Javascript箭头功能而不是...的

时间:2017-09-16 13:22:19

标签: javascript typescript ecmascript-6 arrow-functions

如何使用箭头函数缩短语法?

            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

这样的东西

2 个答案:

答案 0 :(得分:2)

使用Array#find

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

<强>样本

&#13;
&#13;
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;
&#13;
&#13;