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

标签 javascript loops

我想创建一个具有多个“书架”的“库”,但我不知道如何在使用 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);
    }
} 

最佳答案

我不知道为什么你要创建新的架子实例,但首先你应该声明它

// 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
    }
}

关于javascript - 在循环中创建多个具有不同名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210161/

相关文章:

javascript - 使用 jquery 获取引用 url 的一部分

loops - Jekyll — 循环浏览带有标题和编号的帖子

c - 需要帮助在C中使用if else循环创建菜单

Java查找数组列表中最大的整数

php - 在显示其他列之前,在 foreach 循环中显示具有特定非空列的数据库行

javascript - 找不到模块 'chart.js'。)Angular 2

javascript - 在 iframe 上运行 javascript 函数 (execCommand ('SaveAs' ..)

Javascript 改变标签的innerhtml

javascript - 如何在没有 FQL 的情况下检查 Facebook 相册是否已存在

java - 使用循环创建 java jbutton