首页 > 解决方案 > 创建一个包含另一个类的实例数组的类

问题描述

我有一个班级“点”

  let Dot= function (x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

我想创建另一个类“Poly”,其中包含一堆 Dot 类的实例,如下所示:

class Poly {

    constructor(nDots){
        for(let i = 0; i < nDots; i++){
            this.dots[i] = new Dot(Math.floor(Math.random() * 600), Math.floor(Math.random() * 600), Math.floor(Math.random() * 600));
        }
    }
}

但我认为不可能在构造函数中使用 FOR 循环。:) 我的问题有什么解决方案吗?感谢您的关注。

标签: javascript

解决方案


可以for在构造函数中使用循环。你的问题是你没有初始化this.dots数组:

constructor(nDots) {
    this.dots = [];
    for(let i = 0; i < nDots; i++){
        this.dots[i] = /* ... */;
    }
}

顺便说一句,最好使用Array#push填充数组而不是[i]

this.dots.push( /* ... */ );

推荐阅读