我正在尝试显示数组中的 3 个随机值。以下脚本仅从 javaScript 数组返回单个项目。
var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var singleRandom = arrayNum[Math.floor(Math.random() * arrayNum.length)];
alert(singleRandom);
但我想显示数组 arrayNum
中的三个随机值,任何人都可以指导我是否可以使用 javascript 从数组中获取 3 个唯一的随机值?如果有人指导我,我将不胜感激。谢谢
我假设您正在询问如何获得一个由当前数组中的三个元素组成的新数组。
如果您不介意重复的可能性,您可以做一些简单的事情,例如:下面的 getThree
。
但是,如果您不想重复值,可以使用 getUnique
。
var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
function getThree() {
return [
arrayNum[Math.floor(Math.random() * arrayNum.length)],
arrayNum[Math.floor(Math.random() * arrayNum.length)],
arrayNum[Math.floor(Math.random() * arrayNum.length)]
];
}
function getUnique(count) {
// Make a copy of the array
var tmp = arrayNum.slice(arrayNum);
var ret = [];
for (var i = 0; i < count; i++) {
var index = Math.floor(Math.random() * tmp.length);
var removed = tmp.splice(index, 1);
// Since we are only removing one element
ret.push(removed[0]);
}
return ret;
}
console.log(getThree());
console.log("---");
console.log(getUnique(3));