How to extend an existing JavaScript array with another array, without creating a new array

后端 未结 16 2083
深忆病人
深忆病人 2020-11-22 07:38

There doesn\'t seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python\'s extend method.

I want to achieve th

16条回答
  •  借酒劲吻你
    2020-11-22 08:09

    You can do that by simply adding new elements to the array with the help of the push() method.

    let colors = ["Red", "Blue", "Orange"];
    console.log('Array before push: ' + colors);
    // append new value to the array
    colors.push("Green");
    console.log('Array after push : ' + colors);

    Another method is used for appending an element to the beginning of an array is the unshift() function, which adds and returns the new length. It accepts multiple arguments, attaches the indexes of existing elements, and finally returns the new length of an array:

    let colors = ["Red", "Blue", "Orange"];
    console.log('Array before unshift: ' + colors);
    // append new value to the array
    colors.unshift("Black", "Green");
    console.log('Array after unshift : ' + colors);

    There are other methods too. You can check them out here.

提交回复
热议问题