javascript jQuery 从字符串数组中选择一个随机值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6470121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:48:05  来源:igfitidea点击:

jQuery pick a random value from a array of strings

javascriptjqueryarraysrandom

提问by Alex

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')),

easing: randomFrom(array('easeOutElastic', 'easeOutBounce', 'easeOutSince')),

回答by Dogbert

function randomFrom(array) {
  return array[Math.floor(Math.random() * array.length)];
}

// in your code
easing: randomFrom(['easeOutElastic', 'easeOutBounce', 'easeOutSince']),

回答by Naftali aka Neal

Try this:

试试这个:

function randomFrom(arr){
    var randomIndex = Math.floor(Math.random() * arr.length);
    return arr[randomIndex];
}

回答by Aamir Afridi

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/

回答by nonopolarity

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. The first solution here is a solution with O(1).

这就像洗一副牌并返回最上面的牌。但是它的时间复杂度太高了,O(n log n)所以我不会真正使用它,它只是为了好玩。这里的第一个解决方案是使用O(1).