What is the easiest way to insert a new object into an array of objects at the index position 0? No jQuery; MooTools okay; no unshift() because it's undefined in IE according to w3schools.
4 Answers
W3CSchools is really outdated, the unshift method is part of the ECMAScript 3rd Edition standard which was approved and published as of December 1999.
There is no reason to avoid it nowadays, it is supported from IE 5.5 up.
It is safe to use it, even modern libraries like jQuery or MooTools internally use it (you can check the source code :).
var array = [2,3];
array.unshift(1); // returns 3
// modifies array to [1, 2, 3]
This method returns the new array length, and inserts the element passed as argument at the first position of the array.
3 Comments
unshift because w3schools says it is unsupported in IE. As @CMS points out, that is out-of-date: w3schools doesn't even track IE<6 market share any more.Using splice method.
array.splice(index,howmany,element1,.....,elementX);
For inserting, 'howmany' = 0
2 Comments
unshift and concat are simpler than splice for what @JamesBrownIsDead wants to do.I would use unshift() if your intent is to modify the array, otherwise you can use concat() as Kobi suggested (which returns a new array and does not modify the involved arrays):
var arr = [1, 2], newItem = 3;
var newArr = [newItem].concat(arr); // newArr = [1, 2, 3], arr still = [1, 2]
See: concat
unshiftworks on IE: jsbin.com/umolo