javascript JS 将 Object 填充为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18607468/
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
JS fill Object as an array
提问by Ivan Hristev
can you tell me how to fill this element as an array
你能告诉我如何将这个元素填充为数组吗
testdata = [
{
key: "one",
y: 200
},
{
key: "two",
y: 300
}
];
example:
例子:
testdata=[];
testdata[]="one";
testdata[]="two";
采纳答案by Hrishi
It's much better to write a function that constructs a json object. Call it CreateObject and then you can just use a for loop like:
写一个构造json对象的函数会好很多。将其称为 CreateObject,然后您就可以使用 for 循环,例如:
var list = [];
for(var i = 0; i < 10; i++) {
var obj = CreateObject(i); //add other params if you need
list.push(obj);
}
return list;
回答by Dhaval
I think you want two dimensional JS array
我想你想要二维 JS 数组
var items = [[11,22],[33,44],[55,66]];
alert(items[0][0]); // 11;
Or i think you want dictionary object like following
或者我认为你想要像下面这样的字典对象
var dict = []; // create an empty array
dict.push({
key: "keyName",
value: "the value"
});
reference taken from: How to create dictionary and add key value pairs dynamically in Javascript