Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript push multidimensional array

I've got something like that:

    var valueToPush = new Array();     valueToPush["productID"] = productID;     valueToPush["itemColorTitle"] = itemColorTitle;     valueToPush["itemColorPath"] = itemColorPath;      cookie_value_add.push(valueToPush); 

the result is [];

what am i do wrong?

like image 963
sinini Avatar asked Oct 24 '11 18:10

sinini


People also ask

How do you push in a multidimensional array?

Add a new array of multidimensional array :push( ['testing', 'rust', 'c'] ); We display using the javaScript push method to add a new array to the outer array.

Does JavaScript have multidimensional arrays?

Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.

How do you make a 3 by 3 matrix in JavaScript?

If you just use below method to create a 3x3 matrix. Array(3). fill(Array(3). fill(0));


2 Answers

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array(); valueToPush[0] = productID; valueToPush[1] = itemColorTitle; valueToPush[2] = itemColorPath; cookie_value_add.push(valueToPush); 

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same valueToPush["productID"] = productID; valueToPush["itemColorTitle"] = itemColorTitle; valueToPush["itemColorPath"] = itemColorPath; cookie_value_add.push(valueToPush); 

which is equivalent to:

var valueToPush = { }; valueToPush.productID = productID; valueToPush.itemColorTitle = itemColorTitle; valueToPush.itemColorPath = itemColorPath; cookie_value_add.push(valueToPush); 

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

like image 103
Darin Dimitrov Avatar answered Sep 28 '22 08:09

Darin Dimitrov


Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]); 

or

arrayToPush.push([value1, value2, ..., valueN]); 
like image 43
user2560779 Avatar answered Sep 28 '22 06:09

user2560779