[英]Choosing at random from an array but inside a for loop isn't working as expected
我試圖循環瀏覽元素列表並為它們提供隨機的顏色。 但是我不希望他們使用與前一種顏色相同的顏色。
因此,我創建了一個for循環,在其中調用了一個函數來從數組中獲取顏色。 如果顏色與先前的顏色匹配,則不返回,而是再次調用自身以獲取另一種顏色。
問題是,類經常沒有被添加到元素中。 似乎for循環沒有等待它返回並循環到下一個元素,或者我不應該從自身內部再次調用該函數。 不過,我不太確定,如果有人可以提供幫助,那就太好了,這是我到目前為止所擁有的:
/**
* Return int between min and max
* @return number.
*/
function randomIntFromInterval(min, max) {
return Math.floor(Math.random()*(max-min+1)+min);
};
var app = {
init: function(){
var self = this;
this.colorPool = ['blue', 'orange', 'pink'],
this.items = document.querySelectorAll('.js-icon'),
this.oldColor = 'pink',
this.newColor;
for (i = 0; i < this.items.length; i++) {
// Add a Random Color Class.
self.newColor = self.getColor(self.oldColor);
self.items[i].classList.add(self.newColor);
}
},
getColor: function() {
var color = this.colorPool[randomIntFromInterval(0, (this.colorPool.length-1))];
console.log('n= ',color, ' old= ', this.oldColor);
if(color === this.oldColor){
console.log('need to choose another');
this.getColor();
} else {
console.log('return now');
this.oldColor = color;
return color;
}
}
}
app.init();
這是您的錯誤:您需要返回遞歸值。 返回 this.getColor();
if(color === this.oldColor){
console.log('need to choose another');
return this.getColor();
} else {
console.log('return now');
this.oldColor = color;
return color;
}
在您的函數中,只有在第一次找到正確的顏色時才返回它。 當您再次遞歸調用該函數時,它將不再返回顏色。 因此,當您使用遞歸函數時,您需要同時返回基本情況和調用結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.