How to add an object to an array

naser picture naser · Jun 6, 2011 · Viewed 1.1M times · Source

How can I add an object to an array (in javascript or jquery)? For example, what is the problem with this code?

function(){
    var a = new array();
    var b = new object();
    a[0]=b;
}

I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.

  1. How can I save an object in an array?
  2. How can I put an object in an array and save it to a variable?

Answer

John Strickler picture John Strickler · Jun 6, 2011

Put anything into an array using Array.push().

var a=[], b={};
a.push(b);    
// a[0] === b;

Extra information on Arrays

Add more than one item at a time

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add items to the beginning of an array

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Add the contents of one array to another

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Create a new array from the contents of two arrays

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']