how to do a “flat push” in javascript?

前端 未结 4 839
不知归路
不知归路 2020-12-15 04:31

I want to push all individual elements of a source array onto a target array,

target.push(source);

puts just source\'s reference on the tar

4条回答
  •  春和景丽
    2020-12-15 05:15

    apply does what you want:

    var target = [1,2];
    var source = [3,4,5];
    
    target.push.apply(target, source);
    
    alert(target); // 1, 2, 3, 4, 5
    

    MDC - apply

    Calls a function with a given this value and arguments provided as an array.

提交回复
热议问题