[英]jQuery pick a random value from a array of strings
I know how do this in PHP, but in javascript arrays are weird. 我知道在PHP中这是怎么做的,但在javascript数组中很奇怪。
So I have a set of image transitions which have effects that use easing equations. 所以我有一组图像过渡,其效果使用缓动方程。 For certain effects I want to pick up a random value from a array of multiple values:
对于某些效果,我想从多个值的数组中选取一个随机值:
something like: 就像是:
easing: randomFrom(array('easeOutElastic', 'easeOutBounce', 'easeOutSince')),
function randomFrom(array) {
return array[Math.floor(Math.random() * array.length)];
}
// in your code
easing: randomFrom(['easeOutElastic', 'easeOutBounce', 'easeOutSince']),
Try this: 尝试这个:
function randomFrom(arr){
var randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
For a demo I was trying to get a random easing string ;) 对于演示,我试图获得随机缓动字符串;)
function getRandomEasing() {
var easingArr = [];
for(easing in $.easing){
easingArr.push(easing);
}
var rnd = Math.floor(Math.random() * easingArr.length);
return easingArr[rnd];
}
var randomEasing = getRandomEasing();
Fun demo: http://jsfiddle.net/aamir/psWvy/ 有趣的演示: http : //jsfiddle.net/aamir/psWvy/
I am a late comer to this question. 我是这个问题的后来者。 If you don't mind adding a method to
Array
, you can: 如果您不介意向
Array
添加方法,您可以:
Array.prototype.pickARandomElement = function() {
return this[Math.floor(Math.random() * this.length)];
}
test run: 测试运行:
> [10, 123, 777].pickARandomElement()
10
> [10, 123, 777].pickARandomElement()
777
> [10, 123, 777].pickARandomElement()
777
> [10, 123, 777].pickARandomElement()
123
The following is just for fun: 以下只是为了好玩:
Array.prototype.pickARandomElement = function() {
return this.sort(function() { return Math.random() - 0.5; })[0];
}
it is like shuffling a deck of cards and returning the top card. 这就像洗牌一副牌并返回顶牌。 But its time complexity is
O(n log n)
so I wouldn't really use it, and it is just for fun. 但它的时间复杂度是
O(n log n)
所以我不会真正使用它,它只是为了好玩。 The first solution here is a solution with O(1)
. 这里的第一个解决方案是使用
O(1)
的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.