简体   繁体   English

初学者javascript; 带有未定义对象列的for循环

[英]beginner javascript; for loop with array of objects coming out as undefined

Here is my code 这是我的代码

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 (i =0; i<= family.length; i++) {
    console.log (family[i].name);
}

This produces an error: TypeError: Cannot read property 'name' of undefined 这将产生错误:TypeError:无法读取未定义的属性“名称”

Can anyone point me in the right direction from here? 有人可以从这里向我指出正确的方向吗?

You're iterating one too far. 您正在迭代太多。

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

JavaScript arrays start at zero, and the last non-empty cell is at length - 1 . JavaScript数组从零开始,最后一个非空单元格的length - 1 Thus you have to stop iterating when your index is equal to the length, not when it's greater than the length. 因此,您必须在索引等于长度时停止迭代,而不是在索引大于长度时停止迭代。

您应该将测试条件更改为i < family.length ,您将越界。

i < family.length呢?

Change <= to <. 将<=更改为<。 You are exceeding the array limit. 您超出了阵列限制。

It works just fine. 它工作正常。

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

demo: http://jsfiddle.net/285Th/1/ 演示: http : //jsfiddle.net/285Th/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM