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

后端 未结 16 1901
深忆病人
深忆病人 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

    Update 2018: A better answer is a newer one of mine: a.push(...b). Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)


    For those that simply searched for "JavaScript array extend" and got here, you can very well use Array.concat.

    var a = [1, 2, 3];
    a = a.concat([5, 4, 3]);
    

    Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).


    There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:

    const a = [1, 2, 3];
    const b = [...a, 5, 4, 3];
    

    (It also copies.)

提交回复
热议问题