spread operator vs array.concat()

后端 未结 6 894
日久生厌
日久生厌 2020-12-01 04:00

What is the difference between spread operator and array.concat()

6条回答
  •  无人及你
    2020-12-01 04:44

    There is one very important difference between concat and push in that the former does not mutate the underlying array, requiring you to assign the result to the same or different array:

    let things = ['a', 'b', 'c'];
    let moreThings = ['d', 'e'];
    things.concat(moreThings);
    console.log(things); // [ 'a', 'b', 'c' ]
    things.push(...moreThings);
    console.log(things); // [ 'a', 'b', 'c', 'd', 'e' ]
    

    I've seen bugs caused by the assumption that concat changes the array (talking for a friend ;).

提交回复
热议问题