先来看:
var arr = [1,2,3,4,5,undefined,7,8,9,10,11,12,13,14];
var len = arr.length;
console.log(len);
console.log(arr);
console.log(arr[5]);
if(arr[5]){
console.log(arr[5]);
}else{
console.log("b");
}
输出如下
14
(14) [1, 2, 3, 4, 5, undefined, 7, 8, 9, 10, 11, 12, 13, 14]
undefined
b
算法:
var result = [];
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
var len = arr.length;
console.log(len);
while(result.length < 10){
var idx = Math.floor(Math.random()*len);//[0,13]
if(arr[idx]){
console.log(arr[idx]);
result.push(arr[idx]);
arr[idx] = undefined;//加这个是为了防重复,比如result添加了arr数组内的1,就会让1变成underfind,然后去循环其他的,效率来说并不是最好的,不过比较简单好想
}
}
console.log(result);