亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

用js實(shí)現(xiàn)隨機(jī)返回?cái)?shù)組的一個(gè)元素

 更新時(shí)間:2007年08月13日 19:50:42   作者:  
js實(shí)現(xiàn)隨機(jī)返回?cái)?shù)組的一個(gè)元素,這是個(gè)奇妙的方法。適合做標(biāo)題性質(zhì)文字的隨機(jī)輪換顯示
復(fù)制代碼 代碼如下:

<SCRIPT LANGUAGE="JavaScript">
<!--
var test = ["aa","bb","cc","dd","ee"];
document.write(test[Math.floor(Math.random()*test.length)]);
setInterval("location.reload()",1000);
//-->
</SCRIPT>

這是個(gè)奇妙的方法。適合做標(biāo)題性質(zhì)文字的隨機(jī)輪換顯示。

有兩種不同的方式實(shí)現(xiàn):

一、隨機(jī)取單個(gè),二、讓整個(gè)數(shù)組隨機(jī)排序

注意:[ ] 符號在javascript中定義一個(gè)數(shù)組,{ } 則定義一個(gè)對象

隨機(jī)取得數(shù)組里面的某一個(gè):

復(fù)制代碼 代碼如下:

<script type="text/javascript">
//隨機(jī)取得數(shù)組中的一個(gè)
var Arr = ["a","b","c","d"]; 
var n = Math.floor(Math.random() * Arr.length + 1)-1; 
alert(Arr[n]); 
</script> 

隨機(jī)排序整個(gè)數(shù)組Array:

復(fù)制代碼 代碼如下:

<script type="text/javascript"> 
//隨機(jī)排序整個(gè)數(shù)組
var Arr1=[1,2,3,4,5,6,7,8,9,10,22,33,55,77,88,99]; 
Arr1.sort(function(){return Math.random()>0.5?-1:1;}); 
alert(Arr1); 
</script> 

==========================================

PHP 里面有個(gè)非常方便的打亂數(shù)組的函數(shù) shuffle() ,這個(gè)功能在許多情況下都會用到,但 javascript 的數(shù)組卻沒有這個(gè)方法,沒有不要緊,可以擴(kuò)展一個(gè),自己動手,豐衣足食嘛。

復(fù)制代碼 代碼如下:

<script type="text/javascript">
//<![CDATA[
var shuffle = function(v){
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write("A = ", a.join(","), "<br><br>shuffle(A) = ", shuffle(a));
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
document.write("<br>A.shuffle() = ", a.shuffle());
//]]>
</script>

相關(guān)文章

最新評論