可能重复:
How do I create Javascript array(JSON format) dynamically?
我正在尝试创建以下内容:
var employees = {"accounting": [ // accounting is an array in employees.
{ "firstName" : "John", // First element
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary", // Second Element
"lastName" : "Smith",
"age" : 32 }
] // End "accounting" array.
} // End Employees
我开始时:
var employees=new Array();
如何继续动态追加数组(可能会将firstName更改为变量)?
答案 0 :(得分:7)
var employees = {accounting: []};
employees.accounting.push({
"firstName" : "New",
"lastName" : "Employee",
"age" : 18
});
答案 1 :(得分:2)
employees.accounting.push({ "firstName" : "New", // First element
"lastName" : "Person",
"age" : 55 });
答案 2 :(得分:0)
var urNewFirstName='new john';
employees.accounting[0].firstName = urNewFistName;
答案 3 :(得分:0)
function Employee(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
var employees = {};
employees.accounting = [];
employees.accounting.push(new Employee('John', 'Doe', 23));
employees.accounting.push(new Employee('Mary', 'Smith', 32));