如何在Javascript或Jquery中从数组中选择随机值?

我试图从数组中显示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)); 

你可以尝试这样的事情:

逻辑:

  • 创建临时数组,使其不替换原始值。
  • 计算随机数并使用% array.length来查找正确的索引。
  • 使用array.splice(index, 1)从临时数组中删除元素,以便它不会重复。
 var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; function getRandomValues(arr, count){ var result = []; var _tmp = arr.slice(); for(var i = 0; i 

for()迭代随机选择

 var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var selected = []; for (var i = 0; i < 3; i++){ selected[i] = arrayNum[Math.floor(Math.random() * arrayNum.length)]; } console.log(selected); 

你可以这样做:

 var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var singleRandom = []; for (var i = 0; i < 3; i++) { singleRandom.push(Math.floor(Math.random() * arrayNum.length)); } console.log(arrayNum[singleRandom[0]]); console.log(arrayNum[singleRandom[1]]); console.log(arrayNum[singleRandom[2]]);