Javascript javascript推送多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7880257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript push multidimensional array
提问by sinini
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?
我做错了什么?
回答by Darin Dimitrov
Arrays must have zero based integer indexes in JavaScript. So:
JavaScript 中的数组必须具有从零开始的整数索引。所以:
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.
这是每个 JavaScript 开发人员都必须理解的 JavaScript 数组和 JavaScript 对象(它们是关联数组)之间的一个非常基本和关键的区别。
回答by user2560779
Use []
:
使用[]
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
或者
arrayToPush.push([value1, value2, ..., valueN]);
回答by Michael Berkowski
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.
在 JavaScript 中,您尝试使用的键/值存储类型是对象字面量,而不是数组。您错误地创建了一个复合数组对象,该对象恰好具有基于您提供的键名的其他属性,但数组部分不包含任何元素。
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
相反,声明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);