javascript - 在数组文字中使用构造函数创建对象

标签 javascript arrays

我正在尝试使用我的构造函数 Person 创建一个对象,但是当我直接在使用文字表示法的数组中初始化对象时它不起作用。

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

var family = [
    [ new Person("alice", 40)   ],
    [ new Person("bob", 42)     ],
    [ new Person("michelle", 8) ],
    [ new Person("timmy", 6)    ]
];

for (var person in family) {
    console.log(family[person].name);
}

但它只是打印了四次 undefined

我必须使用这个符号:

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

因此它打印出alicebobmichelletimmy

我做错了什么?

最佳答案

你可以只使用这个:

var family = [
     new Person("alice", 40),
     new Person("bob", 42),
     new Person("michelle", 8),
     new Person("timmy", 6)    
];

没有必要将每个 Person 括在方括号中。

现在您可以像下面这样循环遍历数组的项目:

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

我没有使用 for..in 因为它存在的另一个原因是:

The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

关于for...in的更多细节,请查看here .

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

var family = [
         new Person("alice", 40),
         new Person("bob", 42),
         new Person("michelle", 8),
         new Person("timmy", 6)    
    ];

for (var index=0; index<family.length; index++) {
    document.write(family[index].name);
    document.write("</br>");
}

关于javascript - 在数组文字中使用构造函数创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968124/

相关文章:

javascript - FramerJS:重新排序数组

c - 使用指针数组而不是二维数组时出错

javascript - 我的浏览器需要 JavaScript 才能运行

javascript - 无法从 ES6 中的 JSON 数组中删除 key

javascript - 如何避免附加多个事件监听器?

javascript - UseState、UseEffect 不更新 reactjs 中的状态。我正在尝试将随机数添加到状态

c - 尝试创建一个结构数组并从文件加载数据

javascript - 捕获句点但不捕获内部链接

javascript - 对于使用 XMLHttpRequest 更改其内容的页面来说,合适的事件监听器是什么?

python - 如何使用 numpy.savez 将带有子数组的数组保存到单独的 .npy 文件中