从JavaScript中的箭头函数返回数组

时间:2020-04-28 11:43:52

标签: javascript arrays function p5.js arrow-functions

我正在用p5.js中的JavaScript制作太阳能系统生成器,我想从箭头函数返回一个rgb值数组,但是它不起作用。星星是白色,而不是黄色,橙色或红色。

class Star {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = random(50, 70);
    this.color = () => {
      let colorChoice = floor(random(6));
      switch(colorChoice) {
        case 0: case 1: case 2: case 3:
          return [255, 255, 0];
          break;
        case 4:
          return [255, 150, 0];
          break;
        case 5:
          return [255, 0, 0];
          break;
      }
    }
  }

  show() {
    noStroke();
    fill(this.color[0], this.color[1], this.color[2]);
    circle(this.x, this.y, this.size);
  }
}

函数本身或其他地方有问题吗?

1 个答案:

答案 0 :(得分:1)

this.color-是一个函数。尝试将您的show()方法更新为

let color = this.color();
fill(color[0], color[1], color[2]);