【问题标题】:Trying to retrieve an object's color from an array试图从数组中检索对象的颜色
【发布时间】:2018-11-04 02:29:18
【问题描述】:

所以我已经做了几个小时了,我的大脑被炸了,所以我需要一些帮助。

我需要从数组中最近添加的对象中获取颜色值,并将其用于单独的函数。

在 cmets 中,它是目标 #4。我一直无法获得正确的语法,到目前为止谷歌已经完全没用了。

function mousePressed() {
saveSpot();
print(spots);
}

function saveSpot() {
  let newSpot = new Spot (mouseX, mouseY, currentColor());
  spots.push(newSpot);
}

function lastColor() {
 var lastColor = color(255);

 // #4 Return the color of the most recently added Spot in the spots array

return lastColor;
}

function drawLastColor() {
  fill(lastColor());
  textSize(50);
  text("L", 10, 50);
}

function currentColor() {
  return color(0, mouseX, mouseY);
}

class Spot {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.size = 25;
  }

  draw() {
    noStroke();
    fill(this.color);
    ellipse(this.x, this.y, this.size, this.size);
  }
}

如果您需要查看更多代码或需要更多信息,请询问,我会尽力提供。你们可以提供的任何帮助将不胜感激!感谢您的宝贵时间!

【问题讨论】:

    标签: javascript arrays class colors p5.js


    【解决方案1】:

    您可以获取spots 的最后一个元素并获取color 属性。

    function lastColor() {
        return spots[spots.length - 1].color;
    }
    

    检查最后一个元素是否存在。如果不是undefined,则返回。

    function lastColor() {
        var last = spots[spots.length - 1];
        return last && last.color;
    }
    

    【讨论】:

      【解决方案2】:

      如果您需要将最后一个元素添加到数组中,它将是 spots.pop() 由于那里有一个 Spot 对象,请尝试使用 spots.pop().color

      请注意,因为pop 会修改数组。如果您需要查找值,请尝试使用spots[spots.length-1].color

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-21
        • 2012-06-12
        相关资源
        最近更新 更多