Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array.prototype.push vs array.push [duplicate]

I have seen people using two different ways of using different methods of the Array object in javascript.

I mostly use it like so:

arr.push(element1, ..., elementN)

But I have seen people using this:

Array.prototype.push.apply(this,arguments)

I understand that all JavaScript objects inherit the properties and methods from their prototype. The Object.prototype is on the top of the prototype chain.

What are the differences between two approaches and when should each approach be used?

like image 284
Skywalker Avatar asked Oct 27 '15 15:10

Skywalker


2 Answers

The call via .apply() is used when you're interested in using .push() with an object that isn't really an array. A jQuery object, for example, is not really an array instance, but the code mostly maintains a .length property that's enough for it to look like an array, at least as far as .push() and other Array prototype methods are concerned.

For a real array instance, there's no need to do that; the .push() method is directly available via the prototype chain.

So:

var obj = { length: 0 };
Array.prototype.push.apply(obj, ["hello world"]);
console.log(obj[0]); // hello world
like image 72
Pointy Avatar answered Oct 22 '22 14:10

Pointy


I assume you saw Array.prototype.push.apply(this,arguments) in an function like this

function foo() {
    arguments.push = function() {
       Array.prototype.push.apply(this,arguments);    
    } 
    arguments.push(1,2,3);
    //.... 
}

Here this is the foo's arguments, it is just an Array like object, not an Array, it does not have push method. So we should use Array.prototype.push.apply(this,arguments)

like image 2
bpceee Avatar answered Oct 22 '22 15:10

bpceee