Array.push return pushed value?

前端 未结 6 1948
盖世英雄少女心
盖世英雄少女心 2021-01-04 02:30

Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?

I

6条回答
  •  无人及你
    2021-01-04 02:53

    Method push() returns the last element added, which makes it very inconvenient when creating short functions/reducers. Also, push() - is a rather archaic stuff in JS. On ahother hand we have spread operator [...] which is faster and does what you needs: it exactly returns an array.

    // to concat arrays
    const a = [1,2,3];
    const b = [...a, 4, 5];
    console.log(b) // [1, 2, 3, 4, 5];
    
    // to concat and get a length
    const arrA = [1,2,3,4,5];
    const arrB = [6,7,8];
    console.log([0, ...arrA, ...arrB, 9].length); // 10
    
    // to reduce
    const arr = ["red", "green", "blue"];
    const liArr = arr.reduce( (acc,cur) => [...acc, `
  • ${cur}
  • `],[]); console.log(liArr); //[ "
  • red
  • ", //"
  • green
  • ", //"
  • blue
  • " ]

提交回复
热议问题