1

这是代码:

// The Person constructor
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// Now we can make an array of peoples
var family = new Array();
family[0] = Person("alice", 40);
family[1] = Person("bob", 42);
family[2] = Person("michelle", 8);
family[3] = Person("timmy", 6);

// loop through our new array
for ( i=0; i < family.length; i++; ) {
    console.log(family[i].name)
};

该脚本的预期输出为:

alice
bob
michelle
timmy

但输出是:

未捕获的类型错误:无法读取未定义的属性“名称”(匿名函数)

4

3 回答 3

2

new为每个添加的关键字添加一个关键字,并在-loop中Person删除额外的(在 之后);fori++

// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

// loop through our new array
for ( i=0; i < family.length; i++ ) {
    console.log(family[i].name);       // Also, added a semicolon here. Not required, but it's good practice to close your lines.
};

现在将记录:

爱丽丝鲍勃米
歇尔蒂米
_
_

于 2013-01-03T09:04:31.567 回答
0
// Our Person constructor
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

console.info(family);
// loop through our new array
for ( i=0; i < family.length; i++ ) {
    console.log(family[i].name)
};
于 2013-01-03T09:05:15.543 回答
0

我做了这样的事情:

// Our Person constructor
var Person = function(name,age) {
    this.age = age;
    this.name = name;
};

// Now we can make an array of people
var family = new Array();
    family[0] = new Person("alice",40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle",8);
    family[3] = new Person("timmy",6);

// loop through our new array
for (var famloop in family) {
    console.log(family[famloop].name);
}
于 2013-01-10T13:31:59.473 回答