Get random item from JavaScript array [duplicate]

2018-12-31 05:21发布

This question already has an answer here:

var items = Array(523,3452,334,31,...5346);

How do I get random item from items?

13条回答
冷夜・残月
2楼-- · 2018-12-31 06:17

1. solution: define Array prototype

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

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

list = [2,3,5]
list.random()

2. solution: define custom function that accepts list and returns element

get_random = function (list) {
  return list[Math.floor((Math.random()*list.length))];
} 

get_random([2,3,5])
查看更多
大哥的爱人
3楼-- · 2018-12-31 06:18

If you are using node.js, you can use unique-random-array. It simply picks something random from an array.

查看更多
君临天下
4楼-- · 2018-12-31 06:18

An alternate way would be to add a method to the Array prototype:

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

 var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
 var chosen_team = teams.random(teams.length)
 alert(chosen_team)
查看更多
明月照影归
5楼-- · 2018-12-31 06:19
var random = items[Math.floor(Math.random()*items.length)]
查看更多
几人难应
6楼-- · 2018-12-31 06:22

If you really must use jQuery to solve this problem:

(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
})(jQuery);

var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);

This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!

For extra fun, the array return is generated by calling the function recursively based on the array's length :)

Working demo at http://jsfiddle.net/2eyQX/

查看更多
零度萤火
7楼-- · 2018-12-31 06:24
const ArrayRandomModule = {
  // get random item from array
  random: function (array) {
    return array[Math.random() * array.length | 0];
  },

  // [mutate]: extract from given array a random item
  pick: function (array, i) {
    return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
  },

  // [mutate]: shuffle the given array
  shuffle: function (array) {
    for (var i = array.length; i > 0; --i)
      array.push(array.splice(Math.random() * i | 0, 1)[0]);
    return array;
  }
}
查看更多
登录 后发表回答