簡體   English   中英

嘗試從數組中檢索對象的顏色

[英]Trying to retrieve an object's color from an array

所以我已經呆了好幾個小時了,我的大腦也炸了,所以我可以使用一些幫助。

我需要從數組中最近添加的對象中獲取顏色值,並將其用於單獨的函數。

在評論中,它是目標4。 我一直無法正確使用語法,到目前為止Google完全沒有用。

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);
  }
}

如果您需要查看更多代碼或需要更多信息,請詢問,我將盡力提供。 你們能提供的任何幫助將不勝感激! 感謝您的時間!

您可以采用spots的最后一個元素並采用color屬性。

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

用檢查最后一個元素是否存在。 如果undefined則返回。

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

如果您需要將最后一個元素添加到數組中,它將是spots.pop()既然那里有一個Spot對象,請嘗試使用spots.pop().color

請注意,因為pop會修改數組到位。 如果您需要查找值,請嘗試使用spots[spots.length-1].color

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM