试图从数组中检索对象的颜色

时间:2018-05-24 19:05:47

标签: javascript arrays class colors p5.js

所以我已经在这里工作了好几个小时,我的大脑被炸了,所以我可以使用一些帮助。

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

在评论中它的目标#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);
  }
}

如果您需要查看更多代码或需要更多信息,请询问,我会尽我所能。你们给予的任何帮助都将不胜感激!谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:1)

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

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

相关问题