简体   繁体   English

循环使用对象中的数组

[英]Loop for with arrays in Objects

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

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

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

在此处输入图片说明

I need help with the error i am getting here . 我需要帮助我解决这里出现的错误 In this task i needed to create a for-loop that loops through the family array and prints out the name property for each family member in order of creation. 在此任务中,我需要创建一个for循环,该循环遍历family数组并按创建顺序为每个family成员打印出name属性。

Try to close the curly brace of constructor properly, 尝试正确关闭构造函数的花括号,

  function Person(name,age){ // Our Person constructor
    this.name = name ;
    this.age = age ;
  }
//^------ close it here.
var family = new Array(); // Now we can make an array of people
family [1] = new Person("alice",40);
family [2] = new Person("bob",42);
family [3] = new Person("michelle",8);
family [4] = new Person("timmy",6);

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

You are not closing the bracket properly, As a result, whenever you are creating an object, the constructor is getting called, again you are creating an object inside of it and so on. 您没有正确合上支架,因此,无论何时创建对象,都会调用构造函数,再次在其内部创建对象,依此类推。 So maximum call stack size exceeded. 因此超出了最大调用堆栈大小。 And error got raised. 错误出现了。

As a side note, your array will look like, [undefined x 1, obj, obj .. n] since you are ignoring the zeroth index of it. 附带说明一下,由于您忽略了数组的第零个索引,因此数组看起来像[undefined x 1, obj, obj .. n] So its better to use push, family.push(new Person("alice", 40)); 因此最好使用push, family.push(new Person("alice", 40));

function Person(name, age) { // Our Person constructor
    this.name = name;
    this.age = age;
} // <--- "}" must be here

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

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

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

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