【问题标题】:What is "..." in Angular2? What its purpose? [duplicate]Angular2中的“...”是什么?它的目的是什么? [复制]
【发布时间】:2020-02-27 12:34:47
【问题描述】:

Angular 中的 ... 是什么?它叫什么? 我在想 addFlash 方法中的 "...flash" 有什么用,它是 array.push() 中的一个参数?

如果我们可以使用 this 关键字,为什么在 toggleFlash 方法中还有“...”?

flashs: IFlash[] = [];

flashs$ = new BehaviorSubject<IFlash[]>(this.flashs);

addFlash(flash: IFlash) {
    this.flashs.push({
        ...flash,
        show: false,
        id: getRandomNumber()
    });
}

toggleFlash(id: number) {
    const index = this.flashs.findIndex(flash => flash.id === id);
    this.flashs = [
        ...this.flashs.slice(0, index),
        {
            ...this.flashs[index],
            show: !this.flashs[index].show
        },
        ...this.flashs.slice(index + 1)
    ];
    this.flashs$.next(this.flashs);
}

【问题讨论】:

标签: angular typescript


【解决方案1】:

... 在您的代码中是 es6 Spread_syntax ...this.flashs 会将 this.flashs 项目添加到您使用它的数组中,而 {...this.flashs[index] 会将给定索引处的对象的属性添加到您所在的对象'r 使用它阅读下面代码中的 cmets 以获得进一步解释

 this.flashs = [
        ...this.flashs.slice(0, index),//slice flashs array and add result items here like obj1,obj2....
        {
            ...this.flashs[index],//get object at given index and add that object properties here like prop1:val,prop2:val,...
            show: !this.flashs[index].show
        },
        ...this.flashs.slice(index + 1)
    ];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 2011-03-05
    • 2015-08-07
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    相关资源
    最近更新 更多