javascript - Using array.prototype.push vs array.push -


this question has answer here:

i have seen people using 2 different ways of using different methods of array object in javascript.

i use so:

arr.push(element1, ..., elementn) 

but have seen people using this:

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

i understand javascript objects inherit properties , methods prototype. object.prototype on top of prototype chain.

what differences between 2 approaches , when should each approach used?

the call via .apply() used when you're interested in using .push() object isn't array. jquery object, example, not array instance, code maintains .length property that's enough look like array, @ least far .push() , other array prototype methods concerned.

for real array instance, there's no need that; .push() method directly available via prototype chain.

so:

var obj = { length: 0 }; array.prototype.push.apply(obj, ["hello world"]); console.log(obj[0]); // hello world 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -