我有阵列
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
我如何使用javascript回显它的4个随机元素?
答案 0 :(得分:1)
如果你想要不同的元素,你可以从数组中一次提取一个
function extractRandomElement(arr) {
var index = Math.floor(Math.random() * arr.length);
return arr.splice(index, 1)[0];
}
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
var arrCopy = arr.slice(0); // copy the array so the original is unchanged
var result = [];
var N = 4;
for (var i=0; i<N; i++) {
result.push(extractRandomElement(arrCopy));
}
console.log(result);
另一种方法是对数组进行随机排序(随机排序),然后得到前4个元素:
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
var arrCopy = arr.slice(0); // copy the array so the original is unchanged
var N = 4;
var result = arrCopy.sort(function(){ return Math.random()-0.5; }).slice(N);
console.log(result);
这个重复这个问题的答案非常好: https://stackoverflow.com/a/7159251/1669279
这是对上述第一种方法的改进:
function extractRandomElement(arr) {
var index = Math.floor(Math.random() * arr.length);
var retVal = arr[index];
arr[index] = arr.pop();
return retVal;
}
答案 1 :(得分:0)
您可以使用以下代码获取随机元素:
arr[Math.floor(Math.random() * arr.length)];
答案 2 :(得分:0)
这个怎么样:
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
arrLength = arr.length;
var randomNummer = Math.floor(Math.random()*arrLength);
alert(arr[randomNummer]);
<强> jsFiddle 强>
答案 3 :(得分:0)
如果您尝试获取该数组的4个唯一元素,则应始终删除随机检索的元素:
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'],
random_values = [];
for (var i = 0; i < 4; i++ ) {
var length = arr.length,
random = Math.floor(Math.random()*length+1);
random_values.push(arr[random]);
// Remove the already selected element from the arr array
arr.splice(random, 1);
}
console.log(random_values);
答案 4 :(得分:0)
您可以使用以下代码获取4个随机元素:
var element1 = arr[Math.floor(Math.random() * arr.length)];
var element2 = arr[Math.floor(Math.random() * arr.length)];
var element3 = arr[Math.floor(Math.random() * arr.length)];
var element4 = arr[Math.floor(Math.random() * arr.length)];