码迷,mamicode.com
首页 > 编程语言 > 详细

一些算法案例,如一个数组里取是个随机数(前端网备份)

时间:2019-06-10 11:51:31      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:最好   bsp   lse   push   rand   前端   先来   比较   随机   

先来看:
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);

一些算法案例,如一个数组里取是个随机数(前端网备份)

标签:最好   bsp   lse   push   rand   前端   先来   比较   随机   

原文地址:https://www.cnblogs.com/lsc-boke/p/10996857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!