获取到随机数,并且每次获取的随机数和上一次获取的不相同
<!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>