How can I add new array elements at the beginning of an array in Javascript?

前端 未结 13 725
一生所求
一生所求 2020-11-22 13:31

I have a need to add or prepend elements at the beginning of an array.

For example, if my array looks like below:

[23, 45, 12, 67]

13条回答
  •  深忆病人
    2020-11-22 14:01

    Cheatsheet to prepend new element(s) into the array

    1. Array#unshift

    const list = [23, 45, 12, 67];
    
    list.unshift(34);
    
    console.log(list); // [34, 23, 45, 12, 67];

    2. Array#splice

    const list = [23, 45, 12, 67];
    
    list.splice(0, 0, 34);
    
    console.log(list); // [34, 23, 45, 12, 67];

    3. ES6 spread...

    const list = [23, 45, 12, 67];
    const newList = [34, ...list];
    
    console.log(newList); // [34, 23, 45, 12, 67];

    4. Array#concat

    const list = [23, 45, 12, 67];
    const newList = [32].concat(list);
    
    console.log(newList); // [34, 23, 45, 12, 67];

    Note: In each of these examples, you can prepend multiple items by providing more items to insert.

提交回复
热议问题