Javascript创建一个数组来随机化数组值而不重复?

时间:2011-11-08 14:59:02

标签: javascript arrays random

我必须生成一个长度为3的数组[3,2,1] ..从长度为4的数组中随机地说[1,2,3,4]使用java脚本。

  var ele=[1,2,3,4];

我必须生成一个新的数组var three = new Array(3);

数组“three”的值应该是随机化而不是数组“ele”的重复。

 ex three=[3,2,4]... 

这是我试过的代码,

var tempArray=[1,2,3,4];
var set_bf =[];
for(var k=0;k<tempArray.length;k++){
    var rand=(Math.round((Math.random()*tempArray.length)));
    set_bf.push(rand);
    console.log('male :'+rand);
    var idx = tempArray.indexOf(rand);
    if(idx!=-1) tempArray.splice(idx, 1);
}

1 个答案:

答案 0 :(得分:0)

我想你想从另一个数组中选择随机条目?

var rand = myArray[Math.floor(Math.random() * myArray.length)];

这将为您提供数组myArray中的随机元素,这至少应该指向正确的方向

相关问题