我有数组
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
如何使用 javascript 回显它的 4 个随机元素?
我有数组
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
如何使用 javascript 回显它的 4 个随机元素?
如果你想要不同的元素,你可以从数组中一次提取一个
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;
}
您可以使用以下代码获取随机元素:
arr[Math.floor(Math.random() * arr.length)];
那这个呢:
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
arrLength = arr.length;
var randomNummer = Math.floor(Math.random()*arrLength);
alert(arr[randomNummer]);
如果您尝试获取该数组的 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 个随机元素:
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)];