I've seen the Array's push method used to replace concatenation, but I'm not entirely sure how it works.
var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a,b);
How does this concatenate in place rather than returning a new array?
I've seen the Array's push method used to replace concatenation, but I'm not entirely sure how it works.
var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a,b);
How does this concatenate in place rather than returning a new array?
Share Improve this question asked Dec 26, 2012 at 22:36 Jeff StoreyJeff Storey 57.2k74 gold badges242 silver badges412 bronze badges 02 Answers
Reset to default 15.apply()
takes two arguments:
fun.apply(thisArg[, argsArray])
You're passing a
as your this
object and b
as your argument list, so your code is really calling .push()
with the elements of b
as your arguments:
var a = [1, 2, 3];
a.push(4, 5, 6);
Now, .push()
just mutates your original array.
Using this
. To try to describe it see this customPush function.
function customPush() {
var i = 0,
len = arguments.length;
for(; i < len; i++) {
this[this.length] = arguments[i];
}
};
var a = [1,2,3];
var b = [4,5,6];
customPush.apply(a,b);