Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript arrays

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.

like image 200
JamesBrownIsDead Avatar asked Feb 04 '10 05:02

JamesBrownIsDead


People also ask

What are JavaScript arrays?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements".

How many types of arrays are there in JavaScript?

Arrays are just regular objects In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type).

Are arrays lists in JavaScript?

In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods.


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

like image 159
Christian C. Salvadó Avatar answered Oct 18 '22 11:10

Christian C. Salvadó


Using splice method.

array.splice(index,howmany,element1,.....,elementX);

For inserting, 'howmany' = 0

like image 26
o.k.w Avatar answered Oct 18 '22 10:10

o.k.w