Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an object to an array

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?
like image 332
naser Avatar asked Jun 06 '11 15:06

naser


1 Answers

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'] 
like image 83
John Strickler Avatar answered Sep 25 '22 02:09

John Strickler