Javascript 在具有不同名称的循环中创建多个对象

Javascript 在具有不同名称的循环中创建多个对象,javascript,loops,Javascript,Loops,我想创建一个包含多个“工具架”的“库”,但我不知道如何在使用for循环创建每个工具架时以不同的名称命名: function library(initLibraryName, initNumberOfShelves, initNumberOfBooks) { this.name = initLibraryName; this.numberOfShelves = initNumberOfShelves; this.numberOfBooks = initNumberOfBoo

我想创建一个包含多个“工具架”的“库”,但我不知道如何在使用for循环创建每个工具架时以不同的名称命名:

function library(initLibraryName, initNumberOfShelves, initNumberOfBooks)
{
    this.name = initLibraryName;
    this.numberOfShelves = initNumberOfShelves;
    this.numberOfBooks = initNumberOfBooks;
    for (var i = 0; i < numberOfShelves; i++)
    {
       this.shelf = new shelf(i, numberOfBooks/numberOfShelves);
    }
} 
函数库(initLibraryName、initNumberOfShelfs、initNumberOfBooks)
{
this.name=initLibraryName;
this.numberofsheels=initnumberofsheels;
this.numberOfBooks=initNumberOfBooks;
对于(变量i=0;i
我不知道为什么要创建shelf的新实例,但首先应该声明它

// by convention constructor name should start with uppercase letter
function Library(initLibraryName, initNumberOfShelves, initNumberOfBooks) {
    this.name = initLibraryName;
    this.numberOfShelves = initNumberOfShelves;
    this.numberOfBooks = initNumberOfBooks;
    this.shelf = []; // at first you need to define an array
    for (var i = 0; i < numberOfShelves; i++) {
        // then push Shelf instances to an array
        this.shelf.push(new Shelf(i, this.numberOfBooks / this.numberOfShelves)); 
    }
}

function Shelf(arg1, arg2) {
    this.prop1 = arg1;
    this.prop2 = arg2;
    this.method = function () {
        // some logic
    }
}
//按照约定,构造函数名称应以大写字母开头
函数库(initLibraryName、initNumberOfShelfs、initNumberOfBooks){
this.name=initLibraryName;
this.numberofsheels=initnumberofsheels;
this.numberOfBooks=initNumberOfBooks;
this.shelf=[];//首先需要定义一个数组
对于(变量i=0;i
多亏了:

我现在意识到我需要在我的库类中有一个架子数组,并且你不能仅仅在JS中创建多个对象作为一个函数的一部分


感谢埃尔克兰斯指出后者

您正在为每个迭代分配
this.shelf
。将它们放在一个数组中。只需使用关联array@EdHeal,在JS中没有这样的东西。@Andy-是的,有-看那是一个对象。虽然这对其他语言的程序员来说很有帮助,但是JS中仍然没有关联数组。这是我在stackoverflow上的第一篇文章,很高兴成为社区的一员!