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?
.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With