jQuery随机数组数与上一个不同

jQuery random array number different from the last

本文关键字:上一个 随机 数组 jQuery      更新时间:2023-09-26

我正在将随机背景颜色(来自 3 个调色板)应用于页面的不同部分。但是,我想确保相同的颜色不会连续出现两次。

我以为有点do while循环会起作用,但从外观上看,它并不完全存在。

var colours = new Array('#FF5A5A', '#FFBE0D', '#00DDB8');    
var divs = $('.row');
var last;
var next;
// for each section
divs.each(function(i){
    // get a random colour
    do {
        next = Math.floor(Math.random()*3);
        // if it's the same as the last one, try again!
        } while( next === last ) {
            next = Math.floor(Math.random()*3);
        }
        // when it's different to the last one, set it
        $(this).css('background-color', colours[next] );
        // tell it this is the last one now
        next = last;
});

有什么想法吗?

这是一种语法错误 - 您无法决定是想要一个 do-while-loop 还是一个普通的 while-loop?你放在那里的东西将被解释为一个简单的块:

do {
    next = Math.floor(Math.random()*3);
} while( next === last ) // end of the do-while-loop!
// Block here - the braces could be omitted as well:
{
    next = Math.floor(Math.random()*3);
}
$(this).css('background-color', colours[next] );
…

这将正确计算与上一个不同的数字,但随后它将用一个新的(不受限制的)随机数覆盖它。此外,分配next = last;与您想要的相反。

因此,请将脚本更改为

do {
    next = Math.floor(Math.random()*3);
} while( next === last ) // if it's the same as the last one, try again!
// tell it this is the last one now
last = next;
// now that we've made sure it's different from the last one, set it
$(this).css('background-color', colours[next] );

已修订 - (因为我觉得自己可以接受挑战!) http://jsfiddle.net/6vXZH/2/

var last, colours = ['#ff5a5a', '#ffbe0d', '#00ddb8'];    
$('.row').each(function() {
  var color = colours.splice(~~(Math.random()*colours.length), 1)[0];
  $(this).css('background-color', color);   
  last && colours.push(last), last = color;
});

希望这有帮助! 如果你愿意,我很乐意给你一个一个游戏。

使用一点数组魔法,无需内部循环(http://jsfiddle.net/6vXZH/1/) -

var colours = ['#ff5a5a', '#ffbe0d', '#00ddb8'];    
var used = [];
// for each section
$('.row').each(function(i){
  var color = colours.splice(~~(Math.random()*colours.length), 1)[0];
  $(this).css('background-color', color);
  used.push(color);
  if(used.length > 1) {
    colours.push(used.shift());
  }
});

在函数之前定义下一个和最后一个会更好。

var next=last=Math.floor(Math.random()*3);
$divs.each(function(i){        
    do {
        next = Math.floor(Math.random()*3);
    } while( next === last );  
    $(this).css('background-color', colours[next] );
    next = last;
});
{
var colours     = ['#FF5A5A', '#FFBE0D', '#00DDB8'],
    divs        = $('.row'),
    coloursSize = colours.length,
    last,
    next;

divs.each(function(i){
// get a random colour
    do {
            next = Math.floor( Math.random() * coloursSize );
            // if it's the same as the last one, try again!
        } while( next === last ) 
        // when it's different to the last one, set it
        $(this).css('background-color', colours[next] );
        // tell it this is the last one now
        last = next;
});

}