admin管理员组文章数量:1289635
So I want to declare a javascript array with multiple fields.
For example I know you can do something like
var data = [
{
"field one": "a",
"field two": "b",
},
{
"field one": "c",
"field two": "d",
}
]
However, I don't know to do create such an array dynamically so that I don't have to initialize the fields at declaration time.
So I want to declare a javascript array with multiple fields.
For example I know you can do something like
var data = [
{
"field one": "a",
"field two": "b",
},
{
"field one": "c",
"field two": "d",
}
]
However, I don't know to do create such an array dynamically so that I don't have to initialize the fields at declaration time.
Share Improve this question asked Mar 15, 2013 at 3:46 user1782677user1782677 2,0075 gold badges27 silver badges48 bronze badges3 Answers
Reset to default 6You can add values dynamically to an array using the push()
method.
var data = [];
....
....
data.push({
"field one": "a",
"field two": "b",
})
Also if you want to add keys to an existing object dynamically, you can use the []
syntax
var obj = {};
...
obj['field one'] = 'a';
obj['field two'] = 'b';
data.push(obj)
Each individual array element is a JavaScript Object. You can create new fields using dot or bracket syntax:
var obj = {};
obj.fieldone = "one";
obj["field two"] = "two";
In your case you have to use bracket notation because of the space.
You can insert newly created objects into the array using .push
:
data.push(obj);
You can then access individual fields:
data[0]["field one"] == "a";
Try this:
var data = [];
var fields = ["one", "two"];
var length = fields.length;
var char = 97; // a
for (var i = 0; i < 2; i++) {
var object = {};
for (var j = 0; j < length; j++) {
object["field " + fields[j]] = String.fromCharCode(char++);
}
data.push(object);
}
See the demo here: http://jsfiddle/yqg3D/
本文标签: declaring javascript array with multiple fieldsStack Overflow
版权声明:本文标题:declaring javascript array with multiple fields - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741447512a2379288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论