javascript - js 获取数组内随机三个元素?
ringa_lee
ringa_lee 2017-04-10 17:52:31
0
2
359
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// 随机取得三个元素使得
var newarr = ['e', 'c', 'a'];
ringa_lee
ringa_lee

ringa_lee

reply all(2)
巴扎黑
Array.prototype.random = function () {
  var idx = Math.floor((Math.random()*this.length));
  var n = this.splice(idx,1)[0];
  return n;
}
var i = 0;
var a = [];
while(i++<3){
    a.push(arr.random())
}
console.log(a);
左手右手慢动作

先求数组长度len,然后获得[0,len-1]之间的随机数来做索引,然后用索引去访问数组,就可以获得数组的随机元素

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template