how to do a “flat push” in javascript?

微笑、不失礼 提交于 2019-12-18 01:40:11

问题


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 target list.

In stead I want to do:

for (i = 0; i < source.length; i++) {
    target.push(source[i]);
}

Is there a way in javascript to do this more elegant, without explicitly coding a repetition loop?

And while I'm at it, what is the correct term? I don't think that "flat push" is correct. Googling did not yield any results as source and target are both arrays.


回答1:


You could use the concat method:

var num1 = [1, 2, 3];  
var num2 = [4, 5, 6];  
var num3 = [7, 8, 9];  

// creates array [1, 2, 3, 4, 5, 6, 7, 8, 9]; num1, num2, num3 are unchanged  
var nums = num1.concat(num2, num3);



回答2:


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.




回答3:


You can simply use spread syntax:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];

arr1 = [...arr1, ...arr2];
    // [0, 1, 2, 3, 4, 5]

Alternatively:

var arr1 = ['a', 'b', 'c'];
var arr2 = [1, 2, 3, ...arr1];
        // [1, 2, 3, 'a', 'b', 'c']

Demo:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];

arr1 = [...arr1, ...arr2];
console.log(arr1);


来源:https://stackoverflow.com/questions/4007744/how-to-do-a-flat-push-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!