6

可能重复:
如何动态创建 Javascript 数组(JSON 格式)?

我正在尝试创建以下内容:

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)?

4

4 回答 4

7
var employees = {accounting: []};

employees.accounting.push({
    "firstName" : "New",
    "lastName"  : "Employee",
    "age"       : 18
});
于 2012-08-22T06:08:15.807 回答
2
employees.accounting.push({ "firstName" : "New",  // First element
                      "lastName"  : "Person",
                      "age"       : 55 });
于 2012-08-22T06:08:58.940 回答
0
var urNewFirstName='new john';
employees.accounting[0].firstName = urNewFistName;
于 2012-08-22T06:11:33.217 回答
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));
于 2012-08-22T06:12:22.730 回答