Javascript 可以将数组声明为变量,但在尝试使用concat()时未定义
我有这样一个代码,它按预期工作:Javascript 可以将数组声明为变量,但在尝试使用concat()时未定义,javascript,typescript,Javascript,Typescript,我有这样一个代码,它按预期工作: this.filteredCampaigns = this.allCampaigns.filter((item) => item.status!.includes(filterConditions)) //this.filteredCampaigns is of type Campaign[] | null and allallCampaigns is of type product.Campaign[] .FilteredCampaigns为空,而
this.filteredCampaigns = this.allCampaigns.filter((item) => item.status!.includes(filterConditions))
//this.filteredCampaigns is of type Campaign[] | null and allallCampaigns is of type
product.Campaign[]
.FilteredCampaigns为空,而allCampaigns存储所有数据。当我尝试concat时,它返回未定义且没有编译器错误:
this.filteredCampaigns.concat(this.allCampaigns.filter((item) => item.status!.includes(filterConditions))) //returns undefined
当我尝试推送时,我得到了一个错误
Type 'Campaign[]' has no properties in common with type 'Campaign'.ts(2559)
this.filteredCampaigns.push(this.allCampaigns.filter((item) =>
item.status!.includes(filterConditions))) //returns undefined
如何解决这个问题?我只能声明数组的值,但我需要向其中添加/推送更多不起作用的数据
按以下顺序:
this.filteredCampaigns = this.allCampaigns.filter((item) => item.description?.toLowerCase().includes(filteredString))
this.filteredCampaigns.concat(this.allCampaigns.filter((item) => item.type?.toLowerCase().includes(filteredString)));
您在
push()
上遇到错误,因为您试图将一个数组作为单个元素推送到另一个数组上,Typescript正确地调用了该数组。您应该像这样使用push()
:
this.filteredCampaigns.push(...this.allCampaigns.filter((item) =>
item.status!.includes(filterConditions)))
使用的方法是将该数组的各个元素推送到目标数组上
至于concat()
问题,这是因为您没有将concat()
操作的结果分配给任何对象concat()
不会对调用它的数组进行操作(它不会“就地”操作),但会返回一个值()。如果要使用concat()
,请将值指定给目标数组:
this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter((item) => item.type?.toLowerCase().includes(filteredString)));
您在
push()
上遇到错误,因为您试图将一个数组作为单个元素推送到另一个数组上,Typescript正确地调用了该数组。您应该像这样使用push()
:
this.filteredCampaigns.push(...this.allCampaigns.filter((item) =>
item.status!.includes(filterConditions)))
使用的方法是将该数组的各个元素推送到目标数组上
至于concat()
问题,这是因为您没有将concat()
操作的结果分配给任何对象concat()
不会对调用它的数组进行操作(它不会“就地”操作),但会返回一个值()。如果要使用concat()
,请将值指定给目标数组:
this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter((item) => item.type?.toLowerCase().includes(filteredString)));
不清楚您调用此代码的顺序。调用
.concat()
或.push()
之前,此.filteredCampaigns的值是多少?更新了我的帖子。.concat()或.push()的组合不起作用。最初我声明了该值,然后是.concat()(返回未定义)。因为它不起作用,所以我尝试了.push(),该游戏使我编译错误。如果我改为使用与我尝试push/concat相同的值来声明它,它将起作用。当用作push()
的参数时,您不应该扩展数组吗?而且,concat
不会更改调用它的数组,也不会更改提供的参数-它返回一个浅拷贝。您是否将调用的结果存储在任何位置?不清楚您调用此代码的顺序。调用.concat()
或.push()
之前,此.filteredCampaigns的值是多少?更新了我的帖子。.concat()或.push()的组合不起作用。最初我声明了该值,然后是.concat()(返回未定义)。因为它不起作用,所以我尝试了.push(),该游戏使我编译错误。如果我改为使用与我尝试push/concat相同的值来声明它,它将起作用。当用作push()
的参数时,您不应该扩展数组吗?而且,concat
不会更改调用它的数组,也不会更改提供的参数-它返回一个浅拷贝。您是否将呼叫结果存储在任何位置?