1、数组倒置
<script>
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var newArr = []
for (i = arr.length - 1; i >= 0; i--) {
newArr[newArr.length] = arr[i]
}
console.log(newArr)
</script>
2、数组去重
<script>
function unique(arr) {
var newArr = []
for (var i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i])
}
}
return newArr
}
var demo = unique(['a', 'b', 'b', 'c', 'd'])
console.log(demo)
</script>
3、随机点名
<script>
function getRandom(x, y) {
var sub = Math.abs(y - x)
return Math.floor(Math.random() * (sub + 1)) + Math.min(x, y)
}
// console.log(getRandom(0, 10))
/* var arr = ["小赵", "小钱", "小孙", "小李", "小周", "小吴", "小郑", "小王", "小冯", "小陈", "小朱", "小魏"]
var ran = arr[Math.floor(Math.random() * ((arr.length - 1) + 1))]
console.log(ran);
document.write(ran) */
var arr = ["小赵", "小钱", "小孙", "小李", "小周", "小吴", "小郑", "小王", "小冯", "小陈", "小朱", "小魏"]
var y = arr.length - 1
var x = 0
console.log(arr[getRandom(0, y)])
</script>
标签:arr,console,log,newArr,JS,案例,数组,var,Math
From: https://www.cnblogs.com/qianfanqf/p/16933731.html