我想声明这个对象的数组,我怎么能在javascript中做到这一点?
student[0].name
student[0].age
student[0].id
student[1].name
student[1].age
student[1].id
有人可以提出建议吗?
答案 0 :(得分:3)
var students = [{ name: 'foo', age: 5, id: 1 }, { name: 'bar', age: 6, id: 2 }];
答案 1 :(得分:0)
另一种方式:
var Student = function(n, a, i) {
this.name = n;
this.age = a;
this.id = i;
};
var students = [];
students.push(new Student('foo', 12, 1));
students.push(new Student('bar', 13, 2));
students.push(new Student('baz', 14, 3));
console.log(students[0].name);
console.log(students[2].age);
console.log(students[1].id);
HTH
答案 2 :(得分:0)
首先声明一个对象
这不需要student.js你可以在同一个文件上写对象。
var newStudent = new Object(); //Declare object
newStudent.name="foo";
newStudent.age=20;
newStudent.id=01
//declare array
var student = new Array();
student.push(newStudent);
//later loop array and you can read with
student[0].age