javascript push multidimensional array

前端 未结 3 1756
醉酒成梦
醉酒成梦 2020-12-23 11:20

I\'ve got something like that:

    var valueToPush = new Array();
    valueToPush[\"productID\"] = productID;
    valueToPush[\"itemColorTitle\"] = itemColor         


        
相关标签:
3条回答
  • 2020-12-23 11:58

    In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

    Instead, declare valueToPush as an object and push that onto cookie_value_add:

    // Create valueToPush as an object {} rather than an array []
    var valueToPush = {};
    
    // Add the properties to your object
    // Note, you could also use the valueToPush["productID"] syntax you had
    // above, but this is a more object-like syntax
    valueToPush.productID = productID;
    valueToPush.itemColorTitle = itemColorTitle;
    valueToPush.itemColorPath = itemColorPath;
    
    cookie_value_add.push(valueToPush);
    
    // View the structure of cookie_value_add
    console.dir(cookie_value_add);
    
    0 讨论(0)
  • 2020-12-23 12:01

    Use []:

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

    or

    arrayToPush.push([value1, value2, ..., valueN]);
    
    0 讨论(0)
  • 2020-12-23 12:16

    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.

    0 讨论(0)
提交回复
热议问题