[英]jQuery random array number different from the last
我正在應用隨機背景顏色(從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循環? 你放在那里將被解釋為一個簡單的塊 :
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());
}
});
在函數之前定義next和last會更好。
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;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.