我正在学习javascript而且我正在尝试进行练习,每半秒一个标题的字体会改变。我得到了它的工作,但每一个,它会选择相同的阵列号背靠背。这使得开关看起来像暂停。到目前为止,这是我的代码:
var myFont = [ "times", "helvetica", "verdana", "georgia"];
setInterval(function(){
number = Math.floor(Math.random() * myFont.length);
document.getElementById('hi').style.fontFamily = myFont[number];
}, 500);
您是否将数字变量推送到数组然后使用if语句检查?尝试过,但无法弄明白。任何帮助都非常感谢!
答案 0 :(得分:1)
首先是could shuffle the array,然后遍历随机排序的数组。
shuffle( myFont ).forEach( function( i ) {
document.getElementById('hi').style.fontFamily = myFont[i];
} );
/* or using an interval */
var i = 0,
stop = myFont.length;
setInterval( function(){
document.getElementById('hi').style.fontFamily = myFont[i];
if( i == stop ) {
i = 0;
}
else {
i++;
}
}, 500);
答案 1 :(得分:0)
如果要将数字变量推送到数组,则必须在推送之前在while
循环中检查它。不知怎的,这样:
var myFont = [ "times", "helvetica", "verdana", "georgia"];
var indices = [];
setInterval(function(){
var number;
while (myFont.indexOf(number = Math.floor(Math.random() * myFont.length)) >= 0);
indices.push(number);
document.getElementById('hi').style.fontFamily = myFont[number];
}, 500);
答案 2 :(得分:0)
以下是do...while
循环实际上是最佳选择的极少数情况之一。此代码记录每次迭代使用的index
,如果新的随机索引与前一个相同,则会选择一个新的随机数。它会在条件中断之前执行此操作,即新index
和之前的index
不相同。
//create a collection
var myFont = [ "times", "helvetica", "verdana", "georgia"];
//record the last index used
var lastIndex;
setInterval(function(){
//pick a random number within the collection's range
// make sure it's not the same as the last one used
//using do...while ensures the loop runs once before evaluating the condition
do{
index = Math.floor(Math.random() * myFont.length);
} while(lastIndex === index);
// record the font used
lastIndex = index;
//set the font
document.getElementById('hi').style.fontFamily = myFont[index];
}, 500);