gpt4 book ai didi

javascript - 尝试访问数组: family[i] is undefined

转载 作者:行者123 更新时间:2023-12-03 08:16:42 25 4
gpt4 key购买 nike

我试图按顺序打印每个人的姓名,但我不断收到此错误family[i] is undefined

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

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

for(var i = 0; i <= family.length; i++) {
console.log(family[i].name);
}

最佳答案

您的for循环超出了数组的范围。尝试:

for( var i = 0; i < family.length; i++ )

请记住 array.length将始终高于最大数组索引,因为索引从 0 开始,而长度从 1 开始。

关于javascript - 尝试访问数组: family[i] is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907892/

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