gpt4 book ai didi

javascript - 构造函数或数组或 for 循环中的错误?

转载 作者:行者123 更新时间:2023-11-30 18:12:52 26 4
gpt4 key购买 nike

代码如下:

// 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

但是输出是:

Uncaught TypeError: Cannot read property 'name' of undefined (anonymous function)

最佳答案

为每个添加的 Person 添加一个 new 关键字,并在 for 循环中删除多余的 ; (在 i++ 之后)

// 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.
};

现在将记录:

alice
bob
michelle
timmy

关于javascript - 构造函数或数组或 for 循环中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14135711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com