var items = Array(523, 3452, 334, 31, ..., 5346);
我如何从项目中获得随机项目?
var items = Array(523, 3452, 334, 31, ..., 5346);
我如何从项目中获得随机项目?
当前回答
jQuery就是JavaScript!它只是一个JavaScript框架。例如,要找到一个随机项,只需使用普通的JavaScript,
var randomItem = items[Math.floor(Math.random()*items.length)]
其他回答
var random = items[Math.floor(Math.random()*items.length)]
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
短:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
甚至射击(由José dB.):
let item = items.sort(() => 0.5 - Math.random())[0];
var rndval=items[Math.floor(Math.random()*items.length)];
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;
}
}
如果你真的必须使用jQuery来解决这个问题(注意:你不应该):
(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);
如果给定一个数组,这个插件将返回一个随机元素,或者从[0 ..]N)给定一个数字,或者给定任何其他东西,一个有保证的随机值!
更有趣的是,数组返回是通过基于数组的长度递归调用函数来生成的:)
工作演示:http://jsfiddle.net/2eyQX/