JavaScript推送多维数组

50

我有这样的东西:

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

    cookie_value_add.push(valueToPush);

结果是[];

我做错了什么?


你在哪里看到“the result is []”? - Yaakov Shoham
1
如果你想创建一个数组,请使用[]字面符号而不是new Array。此外,如果您想存储一般的键值对,请使用普通对象而不是数组:var toPush = {}; toPush.productId = ... - hugomg
结果在我的 cookie 中,我将值存储到其中,随着更多的值存储,出现了更多的 []... - sinini
3个回答

84

在JavaScript中,数组必须具有以零为基础的整数索引。因此:

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

或者你想使用对象(也称为关联数组):

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);

等价于:

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

JavaScript中的数组和对象(又称为关联数组)有一种非常基本和关键的区别,每个JavaScript开发人员都必须理解。


数组也是对象。因此,在原始代码中,属性是存在的,而不仅仅是 [] - Yaakov Shoham
@Y. Shoham,是的,数组是对象。只是对于它们来说,[]属性具有特殊的含义。您只能使用基于0的整数,这是OP问题的根源。 - Darin Dimitrov

15

使用 []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
或者
arrayToPush.push([value1, value2, ..., valueN]);

5
在JavaScript中,您尝试使用的键/值存储类型是对象字面量,而不是数组。您错误地创建了一个组合数组对象,该对象基于提供的键名具有其他属性,但数组部分不包含任何元素。
相反,将valueToPush声明为对象,并将其推送到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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接