Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript How Array.prototype.push concatenates

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?

like image 233
Jeff Storey Avatar asked Nov 30 '22 22:11

Jeff Storey


2 Answers

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

like image 127
Blender Avatar answered Dec 10 '22 12:12

Blender


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);
like image 29
Andreas Louv Avatar answered Dec 10 '22 12:12

Andreas Louv