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.
views:
239answers:
4Using splice method.
array.splice(index,howmany,element1,.....,elementX);
For inserting, 'howmany' = 0
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.
You can try this:
var newItem = 3;
arr = [newItem].concat(arr);
Another option is to use push
and reverse the indices - you can easily write an object that does that.
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