从JavaScript数组获取随机值

2020/09/20 13:31 · javascript ·  · 0评论

考虑:

var myArray = ['January', 'February', 'March'];    

如何使用JavaScript从此数组中选择随机值?

这是一个简单的单线

const randomElement = array[Math.floor(Math.random() * array.length)];

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

如果您的项目中已经包含下划线破折号,则可以使用_.sample

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

如果您需要随机获得多个项目,则可以在下划线中将其作为第二个参数传递:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

或使用_.sampleSizelodash中方法:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);

原型法

如果计划大量获取随机值,则可能需要为其定义一个函数。

首先,将其放在您的代码中的某个位置:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

现在:

[1,2,3,4].sample() //=> a random element

根据CC0 1.0许可证的条款向公共领域发布的代码

~~速度比快得多Math.Floor(),因此在使用UI元素生成输出时进行性能优化时,就可以~~赢得比赛。更多信息

var rand = myArray[~~(Math.random() * myArray.length)];

但是,如果您知道该数组将拥有数百万个元素,那么您可能需要重新考虑按位运算符和Math.Floor(),因为按位运算符对大量数字的行为很奇怪。参见下面的示例,对输出进行解释。更多信息(失效链接)

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

假设您要选择一个与上次不同的随机物品(不是真正随机的,但仍然是常见要求)...

以@Markus的答案为基础,我们可以添加另一个原型函数:

Array.prototype.randomDiffElement = function(last) {
   if (this.length == 0) {
      return;
   } else if (this.length == 1) {
      return this[0];
   } else {
      var num = 0;
      do {
         num = Math.floor(Math.random() * this.length);
      } while (this[num] == last);
      return this[num];
   }
}

并像这样实现:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)

如果您有固定值(例如月份名称列表)并且想要单行解决方案

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

数组的第二部分是访问操作,如JavaScript为什么[5,6,8,7] [1,2] = 8中所述?

最短的版本:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[(Math.random() * myArray.length) | 0]

如果要像Pascual的解决方案一样将其写在一行上,另一种解决方案是使用ES6的find函数编写它(基于以下事实n项目中随机选择一个的概率1/n):

var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);

如果有充分理由不将数组仅保存在单独的变量中,请使用该方法进行测试。否则,其他答案(floor(random()*length以及使用单独的函数)是您要走的路。

Faker.js具有许多用于生成随机测试数据的实用程序功能。在测试套件的上下文中,这是一个不错的选择:

const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);

正如评论者所提到的,通常不应在生产代码中使用此库。

编辑数组原型可能是有害的。这是完成这项工作的简单功能。

function getArrayRandomElement (arr) {
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  // The undefined will be returned if the empty array was passed
}

用法:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);

递归的独立函数,可以返回任意数量的项(与lodash.sampleSize相同):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}

要获得加密强度高的随机项目表单数组,请使用

let rndItem = a=> a[rnd()*a.length|0];
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;

var myArray = ['January', 'February', 'March'];

console.log( rndItem(myArray) )

这类似于@Jacob Relkin的解决方案,但比它更笼统:

这是ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

该代码的工作方式是选择一个介于0和数组长度之间的随机数,然后返回该索引处的项目。

var item = myArray[Math.floor(Math.random()*myArray.length)];

或更短的版本:

var item = myArray[(Math.random()*myArray.length)|0];

样例代码:

var myArray = ['January', 'February', 'March'];    
var item = myArray[(Math.random()*myArray.length)|0];
console.log('item:', item);

简单功能:

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

要么

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

要么

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

我认为,与其乱扔原型,不如及时声明它,不如将其暴露在窗口中:

window.choice = function() {
  if (!this.length || this.length == 0) return;
  if (this.length == 1) return this[0];
  return this[Math.floor(Math.random()*this.length)];
}

现在,您可以在应用中的任何位置调用它,如下所示:

var rand = window.choice.call(array)

这样您仍然可以for(x in array)正确使用循环

我已经找到了解决最复杂答案的方法,只需将变量rand连接到另一个变量即可,该变量允许在调用myArray [];时显示该数字。通过删除创建的新数组并解决其复杂性,我提出了一个可行的解决方案:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var myArray = ['January', 'February', 'March', 'April', 'May'];    

var rand = Math.floor(Math.random() * myArray.length);

var concat = myArray[rand];

function random() {
   document.getElementById("demo").innerHTML = (concat);
}
</script>

<button onClick="random();">
Working Random Array generator
</button>

</body>
</html>
static generateMonth() { 
const theDate = ['January', 'February', 'March']; 
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};

您为数组设置了一个常量变量,然后有了另一个常量,该常量在数组的三个对象之间随机选择,然后函数简单地返回结果。

寻找真正的单线我来到这里:

['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })

获取随机元素的通用方法:

let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
let months = random_elems(some_array, 3);

console.log(months);

function random_elems(arr, count) {
  let len = arr.length;
  let lookup = {};
  let tmp = [];

  if (count > len)
    count = len;

  for (let i = 0; i < count; i++) {
    let index;
    do {
      index = ~~(Math.random() * len);
    } while (index in lookup);
    lookup[index] = null;
    tmp.push(arr[index]);
  }

  return tmp;
}

randojs使这一点更加简单易读:

console.log( rando(['January', 'February', 'March']).value );
<script src="https://randojs.com/1.0.0.js"></script>

通过在数组原型上添加方法,您可以轻松获得随机值。

在此示例中,您可以从数组中获取单个或多个随机值。

您可以通过单击摘要按钮来运行测试代码。

Array.prototype.random = function(n){
  if(n&&n>1){
    const a = [];
    for(let i = 0;i<n;i++){
      a.push(this[Math.floor(Math.random()*this.length)]);
    }
    return a;
  } else {
    return this[Math.floor(Math.random()*this.length)];
  }
}

const mySampleArray =  ['a','b','c','d','e','f','g','h'];

mySampleArray.random(); // return any random value etc. 'a', 'b'
mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']

alert(mySampleArray.random());
alert(mySampleArray.random(3));

这是一个如何做的例子:

$scope.ctx.skills = data.result.skills;
    $scope.praiseTextArray = [
    "Hooray",
    "You\'re ready to move to a new skill", 
    "Yahoo! You completed a problem", 
    "You\'re doing great",  
    "You succeeded", 
    "That was a brave effort trying new problems", 
    "Your brain was working hard",
    "All your hard work is paying off",
    "Very nice job!, Let\'s see what you can do next",
    "Well done",
    "That was excellent work",
    "Awesome job",
    "You must feel good about doing such a great job",
    "Right on",
    "Great thinking",
    "Wonderful work",
    "You were right on top of that one",
    "Beautiful job",
    "Way to go",
    "Sensational effort"
  ];

  $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];

创建一个随机值并传递给数组

请尝试以下代码。

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];

alert(Placeholdervalue);
本文地址:http://javascript.askforanswer.com/congjavascriptshuzuhuoqusuijizhi.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!