网站搜索

javascript - 在 Typescript 中这两种数组赋值有什么区别?


我正在开发 Angular 4 应用程序。

我在我的应用程序中发现了下面的代码,但无法确定下面代码的确切用途。

getManagementView(groupField: string) {        
    this.auditList = [...this.auditList.filter(this.filterByRevisit)];
  }

我把它改成下面的代码,两者都能正常工作。

getManagementView(groupField: string) {        
    this.auditList = this.auditList.filter(this.filterByRevisit);
  }

有人能帮我理解上面两个代码块的区别吗?

答案#1

没有什么不同。展开(...) 运算符会拆解数组,并逐一返回元素,然后在 [] 中将它们放回,从而再次创建一个数组。这实际上是额外的操作。

所以 this.auditList.filter(this.filterByRevisit) 返回一个数组,而 [...this.auditList.filter(this.filterByRevisit)] 返回一个展开的数组,并再次生成一个数组。

答案#2

我认为两者之间没有区别。... 会创建一个新数组,filter 已经做过了。

但是如果我接受这个标题:

this.array = this.array      // does nothing, same object
this.array = [...this.array] // creates a new array, though the same content