链式推送以及JavaScript中的过滤器,地图等?

时间:2017-11-10 13:55:30

标签: javascript

我有一个函数返回一个包含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}
        />
      )
    })
)

3 个答案:

答案 0 :(得分:3)

.push(newThiny)将返回number,因此.sort函数会抛出错误,因为它在numbers上不起作用,仅适用于数组。

我建议你改用.concat

.concat(newThiny).sort({ ... })

答案 1 :(得分:1)

  

.push(newThiny)//这不起作用

Push返回数组的长度而不是数组本身。

而不是推送试试concat

.concat([newThiny])

答案 2 :(得分:0)

.push()返回一个数组长度。您可以使用()

包装表达式

参见示例:

&#13;
&#13;
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;
&#13;
&#13;