我有这样的东西:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
结果是[];
我做错了什么?
我有这样的东西:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
结果是[];
我做错了什么?
在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[]
属性具有特殊的含义。您只能使用基于0的整数,这是OP问题的根源。 - Darin Dimitrov使用 []
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
或者arrayToPush.push([value1, value2, ..., valueN]);
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);
var toPush = {}; toPush.productId = ...
- hugomg