我有一个函数返回一个包含filter,sort和map的数组。如何在排序之前将新项目推送到数组中?
当我尝试以下操作时,我得到一个错误,说推送不是一个功能。
return (
myArray
.filter((item) => {
return item.value > 2;
})
.push(newThiny) // This doesn't work
.sort((a, b) => {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
})
.map((item) => {
return (
<ChooseAnExercises
key={item.name}
name={item.name}
active={item.active}
setNumber={this.props.number}
updateValue={this.props.updateValue}
/>
)
})
)
答案 0 :(得分:3)
.push(newThiny)
将返回number
,因此.sort
函数会抛出错误,因为它在numbers
上不起作用,仅适用于数组。
我建议你改用.concat
。
.concat(newThiny).sort({ ... })
答案 1 :(得分:1)
答案 2 :(得分:0)
.push()
返回一个数组长度。您可以使用()
参见示例:
var arr = [ 0, 1, 2, 3, 4];
var arr2 = arr.filter( item => item > 2).push('Some');
console.log(arr2, 'doesnt works. You get the length of array');
(b = arr.filter(item => item > 2)).push('Some');
console.log(b, 'Works Correctly. In Array');
&#13;