Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - how to do a "flat push" in javascript?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...