獲取隨機數並且每次和上一次的不相同
阿新 • • 發佈:2019-02-17
獲取到隨機數,並且每次獲取的隨機數和上一次獲取的不相同
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="btn">點選</button>
</body>
<script src="jquery-1.11.3.js"></script>
<script >
//自定義刪除陣列元素
Array.prototype.del = function (n) {
if (n < 0) return this;
return this.slice(0, n).concat(this.slice(n + 1, this.length));
}
var arr = [1, 2, 3, 4, 5];
var arr2 = [];
$('.btn').click(function () {
if (arr2.length > 0) {
var index = Math.floor((Math.random() * arr2.length));
var temp = arr2[index];
} else {
var index = Math.floor((Math.random() * arr.length));
var temp = arr[index];
}
var num = arr.indexOf(temp);//獲取到取到值的索引
arr2 = arr.del(num);//刪除後成為新的陣列
console.log(temp);
});
</script>
</html>