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

Aya*_*hah 5 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);
Run Code Online (Sandbox Code Playgroud)

但我想从数组中显示三个随机值arrayNum,任何一个指导我是否可以使用javascript从数组中获取3个唯一的随机值?如果有人指导我,我将不胜感激.谢谢

Jer*_*her 7

我将假设您正在询问如何在当前数组中获得由三个元素组成的新数组.

如果你不介意可能的重复,你可以做一些简单的事情,如: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));
Run Code Online (Sandbox Code Playgroud)