我想在方法中生成一次与前一个不同的随机数



我必须在方法中更改背景图像。背景图像来自this.items服务,但是当方法运行时,新的背景图像不应与以前的图像相同。 当我运行此方法时,它会更改图像,但新图像可以与以前的图像相同。我该怎么办?

export class GridManager {
changeBackground() {
var x = Math.floor(Math.random() * document.querySelectorAll(".grid-item").length);
if (this.items[x].backgroundImage != "" && this.items[x].backgroundImage != null) {
document.querySelector(".container").style.backgroundImage = `url('${this.items[x].backgroundImage}')`;
}
}
}

您需要检查该值是否在数组中,如果存在,请将其删除或执行您需要执行的任何操作

function checkItem(array,checkItem){
for( var i=0;i<array.length;i++){
if(array[i] == checkItem){
var removedItem= array.splice(checkItem,1); // your can remove it 
/*or simply do your code here */
}
}
}

有很多解决方案,为了给您另一个这里没有提到的解决方案,您可以执行一个自定义生成随机数,以排除您获得的先前索引。

像这样:

class GridManager {
prevIndex = null;
generateRandom(min, max, excludedIndex) {
var num = Math.floor(Math.random() * (max - min + 1)) + min;
return (num === excludedIndex) ? this.generateRandom(min, max, excludedIndex) : num;
}
changeBackground() {
var x = this.generateRandom(0, document.querySelectorAll(".grid-item").length - 1, this.prevIndex);
this.prevIndex = x;
if (this.items[x].backgroundImage != "" && this.items[x].backgroundImage != null) {
document.querySelector(".container").style.backgroundImage = `url('${this.items[x].backgroundImage}')`;
}
}
}

最新更新