javascript push multidimensional array

sinini picture sinini · Oct 24, 2011 · Viewed 167.8k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 24, 2011

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.