每次在父函式中呼叫函式時,我都會嘗試回圈遍歷陣列中的專案。
const wildColours = ["green", "blue", "orange", "red", "purple", "yellow", "white"]
function drawGame() { // this is drawing elements on the canvas every 100 milliseconds.
nCanvasDrawElements();
drawWildCard();
setTimeout(drawGame, 100);
};
function drawWildCard() {
for (i = 0; i < wildColours.length; i ) {
let wildCycle = wildColours[i];
context.fillStyle = wildCycle;
context.fillRect(wildCardX, wildCardY, tileSize, tileSize);
console.log(wildCycle);
}
};
drawGame();
每次在 drawGame() 中呼叫 drawWildCard() 時,它都會回傳陣列中的所有專案。
我想連續(回圈)通過 wildColours 陣列中的顏色,每次我在 drawGame() 中繪制 drawWildCard() 函式
因此,WildCard 每 100 毫秒回圈通過顏色陣列與所有其他游戲元素。
專案就在這里,我只是在學習編碼。如果有人能解釋答案,我將不勝感激。
uj5u.com熱心網友回復:
您必須跟蹤最后選擇的顏色drawWildCard。在每個drawGame回圈中,您可以更改一次顏色。
為確保回圈使用每種顏色,必須確保在到達陣列末尾后從第一種顏色開始。
您可以通過每次增加索引并將索引的剩余部分除以顏色總數來實作。
nextIndex = (previousIndex 1) % totalNrOfcolors;
const context = document.querySelector("canvas").getContext("2d");
const wildCardX = 0, wildCardY = 0, tileSize = 200;
let wildIndex = 0;
const wildColours = ["green", "blue", "orange", "red", "purple", "yellow", "white"]
function drawGame() { // this is drawing elements on the canvas every 100 milliseconds.
drawWildCard();
setTimeout(drawGame, 100);
};
function drawWildCard() {
const wildCycle = wildColours[wildIndex];
context.fillStyle = wildCycle;
context.fillRect(wildCardX, wildCardY, tileSize, tileSize);
wildIndex = (wildIndex 1) % wildColours.length;
};
drawGame();
<canvas width="200" height="200"></canvas>
uj5u.com熱心網友回復:
我讓它作業,但我不完全確定......我使用的作業......完全。
某種形式的索引余數陣列方法thing-a-majig
array[index % array.length]
我在這個解決方案中找到的Javascript:如何每秒回圈遍歷每個陣列的專案
作業代碼是:
const context = document.querySelector("canvas").getContext("2d");
const wildCardX = 0, wildCardY = 0, tileSize = 200;
const wildColours = ["green", "blue", "orange", "red", "purple", "yellow", "white"]
let index = 0;
function drawGame() { // this is drawing elements on the canvas every 100 milliseconds.
drawWildCard();
setTimeout(drawGame, 100);
};
function drawWildCard() {
context.fillStyle = wildColours[index % wildColours.length];
context.fillRect(wildCardX, wildCardY, tileSize, tileSize);
};
drawGame();
<canvas width="200" height="200"></canvas>
感謝 user3297291 的解釋
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505239.html
標籤:javascript 数组 for循环
上一篇:將回圈與awk相結合
