javascript - 创建一个包含另一个类的实例数组的类
问题描述
我有一个班级“点”
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 循环。:) 我的问题有什么解决方案吗?感谢您的关注。
解决方案
可以for
在构造函数中使用循环。你的问题是你没有初始化this.dots
数组:
constructor(nDots) {
this.dots = [];
for(let i = 0; i < nDots; i++){
this.dots[i] = /* ... */;
}
}
顺便说一句,最好使用Array#push
填充数组而不是[i]
:
this.dots.push( /* ... */ );
推荐阅读
- syntax - 序言中的规则与这些自然语言相协调
- java - 如何从数组列表中获取多语言 android 应用程序
- javascript - 承诺得到解决而不是被拒绝,甚至内部承诺也返回
- excel - 使用 Azure 数据工厂将多个 Excel 数据转换为一个主文件
- python - Django 实时作业
- python - 图像格式不支持 PyGame
- javascript - 在尝试将 firebase 数据返回到另一个页面时,它传递了 undefined
- c - 显示超过 2 个字节的 C char 数据类型
- typescript - 与 tsify 和 firebase 一起使用的 Babelify 不会生成正确的代码
- excel - 如何从excel中两列的数据中找到四分位数