如何在Javascript或Jquery中从数组中选择随机值? [英] How do I select random values from an array in Javascript or Jquery?

查看:40
本文介绍了如何在Javascript或Jquery中从数组中选择随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中显示3个随机值。以下脚本只返回javaScript数组中的单个项目。

  var arrayNum = ['One','two','three' ,'四','五','六','七','八','九']; 
var singleRandom = arrayNum [Math.floor(Math.random()* arrayNum.length)];
alert(singleRandom);

但是我想从数组中显示三个随机值 arrayNum ,任何人都可以指导我使用javascript从阵列中获取3个独特的随机值吗?如果有人指导我,我将不胜感激。谢谢

解决方案

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



如果你不介意可能的重复项,你可以做一些简单的事情,如下所示: getThree



但是,如果您不想重复值,可以使用 getUnique



< pre class =snippet-code-js lang-js prettyprint-override> var arrayNum = ['One','two','three','four','five','six' ,'七','八','九']; 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){//复制数组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); //因为我们只删除了一个元素ret.push(removed [0]); } return ret; }的console.log(getThree());执行console.log( ---);执行console.log(getUnique(3));


I'm trying to show 3 random values from an array. Following script is returning only single item from javaScript array.

var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];  
var singleRandom = arrayNum[Math.floor(Math.random() * arrayNum.length)];
alert(singleRandom);

But I want to show three random value from array arrayNum, can any one guide me is this possible to get 3 unique random values from an array using javascript? I will appreciate if someone guide me. Thank you

解决方案

I am going to assume that you are asking how to get a NEW array made of three elements in your current array.

If you don'd mind the possibly of duplicates, you can do something simple like: getThree below.

However, if you don't want values duplicated, you can use the 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));

这篇关于如何在Javascript或Jquery中从数组中选择随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆