JS随机数组排重

JavaScript011

JS随机数组排重,第1张

用查找数组去重复的效率极低,应该用Object或者JS2015的Set对象做

const s = new Set()

while(s.size<10)

s.add(parseInt(Math.random()*10))

console.log(s) Set { 2, 7, 0, 4, 9, 3, 6, 1, 8, 5 }

读下来你的代码,好像在写随机一共10以内10个数还要去重。就可能不是要为了去重,而是想数组洗牌,就该用常见的算法。

function shuffleArray(a) {

   for(var i=a.length-1 i>0 i--) {

       var j = Math.floor(Math.random() * (i + 1))

       var t= a[i] a[i] = a[j] a[j] = t

   }

}

const a=[]

for(var i=0i<10i++) a.push(i)

shuffleArray(a)

console.log(a) [ 0, 6, 7, 8, 3, 5, 1, 2, 4, 9 ]

var a = [1,2,3,3,4,5,6,7,8,9]

function sendNum(arr)

{

    return arr[Math.floor(Math.random()*arr.length)]

}

sendNum(a)

这样就可以实现每次返回是一个随机数组中的一个数。主要用的就是random的方法。random方法,是返回(0,1] 的数,但取不到1,所以用Math.floor向下取整。