目前只學會兩種簡單的方法,幫助大家實現隨機抽取0-100之間不重復的10個數,具體內容如下
第一種利用數組長度可改寫的特點
思路:可以從0到100的數用for循環出來放在一個數組中,然後將這100個數利用sort()隨機打亂,然後通過將這個數組的length改寫為10,便取到了10個不同的數.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var arr=[];
for(var i=0;i<100;i++){//一個從0到100的數組
arr.push(i);
}
arr.sort(function(){//隨機打亂這個數組
return Math.random()-0.5;
})
arr.length=10;//改寫長度
console.log(arr);//控制台會輸出10個不同的數
</script>
</head>
<body>
</body>
</html>
第二種利用的是json對象的key值唯一的特點.
思路:先分別定義一個保存數組的空數組和一個空的json對象,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
//json對象,key值是唯一的,key值可以為數字
var arr=[];
var json={};
while(arr.length<10){
var k=Math.round(Math.random()*100);
if(!json[k]){
json[k]=true;
arr.push(k);
}
}
console.log(arr)
</script>
</head>
<body>
</body>
</html>
希望本文對大家學習javascript程序設計有所幫助。