从数组中随机选择但在 for 循环内无法按预期工作
Choosing at random from an array but inside a for loop isn't working as expected
我正在尝试循环浏览元素列表并给它们随机颜色。但我不希望他们使用与上一个相同的颜色。
因此我创建了一个 for 循环,在其中调用了一个函数来从数组中获取颜色。如果颜色与之前的颜色匹配,它不会 return 而是再次调用自身以获得另一种颜色。
问题是 class 经常没有添加到元素中。
似乎 for 循环没有等待 return 并循环到下一个元素,或者我不应该从其内部再次调用该函数。不过我不太确定,如果有人能提供帮助那就太好了,这是我目前所知道的:
/**
* 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();
这是您的错误:您需要 return 递归值。
return 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;
}
只有在您的函数第一次找到正确的颜色时,它才会被 returned。当您再次递归调用该函数时,它将不再 return 颜色。因此,当您使用递归函数时,您需要 return 基本情况和调用自身的结果。
我正在尝试循环浏览元素列表并给它们随机颜色。但我不希望他们使用与上一个相同的颜色。
因此我创建了一个 for 循环,在其中调用了一个函数来从数组中获取颜色。如果颜色与之前的颜色匹配,它不会 return 而是再次调用自身以获得另一种颜色。
问题是 class 经常没有添加到元素中。 似乎 for 循环没有等待 return 并循环到下一个元素,或者我不应该从其内部再次调用该函数。不过我不太确定,如果有人能提供帮助那就太好了,这是我目前所知道的:
/**
* 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();
这是您的错误:您需要 return 递归值。 return 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;
}
只有在您的函数第一次找到正确的颜色时,它才会被 returned。当您再次递归调用该函数时,它将不再 return 颜色。因此,当您使用递归函数时,您需要 return 基本情况和调用自身的结果。