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

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

    The answer is super simple.

    >>> a = [1, 2]
    [1, 2]
    >>> b = [3, 4, 5]
    [3, 4, 5]
    >>> SOMETHING HERE
    (The following code will combine the two arrays.)
    
    a = a.concat(b);
    
    >>> a
    [1, 2, 3, 4, 5]
    

    Concat acts very similarly to JavaScript string concatenation. It will return a combination of the parameter you put into the concat function on the end of the array you call the function on. The crux is that you have to assign the returned value to a variable or it gets lost. So for example

    a.concat(b);  <--- This does absolutely nothing since it is just returning the combined arrays, but it doesn't do anything with it.
    

提交回复
热议问题