【问题标题】:Javascript arrow function instead of for...ofJavascript箭头函数而不是for...of
【发布时间】:2017-09-16 13:22:19
【问题描述】:

如何使用箭头函数缩短 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 的东西

【问题讨论】:

    标签: javascript typescript ecmascript-6 arrow-functions


    【解决方案1】:

    使用Array#find

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

    要获得等同于firstOrDefault,您可以将结果短路

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

    【讨论】:

    • 没关系,但我忘了告诉我使用的是 TypeScript(因为 Angular2),所以当我使用 || 时,我的第二个答案出现错误{}“类型 {} 不可分配给类型 Product...”
    【解决方案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);

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 2018-07-06
      • 1970-01-01
      • 2019-01-06
      • 2017-04-18
      • 2019-10-21
      • 2022-01-21
      • 2020-11-30
      相关资源
      最近更新 更多