【问题标题】:How to pick 3 unique arrays?如何选择 3 个独特的数组?
【发布时间】:2013-05-07 13:31:13
【问题描述】:
var arr = ['1','2','3','4'];

如何从arr 中选择 3 个唯一数组?

我只能一一挑选喜欢..

function pick(a){
    var i = Math.floor(Math.random()*a.length);
    return a[i];
}

选取的数组不会重复。

我不知道该怎么做...非常感谢:D

游乐场: http://jsbin.com/ocuhig/1/edit

【问题讨论】:

标签: javascript jquery arrays unique


【解决方案1】:

一种可能的解决方案:

var copy = arr.slice();
while (copy.length > 3) {
    copy.splice(~~(Math.random() * copy.length), 1);
}

还有更可爱的解决方案:

var copy = arr.slice().sort(function() {
    return Math.random() - 0.5;
}).slice(0, 3);

【讨论】:

  • 谢谢!看起来很简单,~~ 是什么?
  • @l2aelba 这是Math.floor的快捷方式。
  • 是的,这应该比我的回答要快!
  • VisioN:我知道您所说的快捷方式是什么意思,但@l2aelba 可能不知道。它不是直接映射到.floor() 方法的捷径。相反,在这种特定情况下,它是实现相同结果的一种更短的方法。在其他情况下,结果可能会有所不同。
  • @squint 是的,从字面上看,你是绝对正确的。 ~~ 是截断小数部分的技巧。
【解决方案2】:
/**
 * Returns a random integer between min and max
 */
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

【讨论】:

    【解决方案3】:

    另一种可能的解决方案:

    var picker = function(a, picked) {
        if ( !picked ) picked = [];
        var randomNumber = Math.floor(Math.random()*a.length);
        if ( picked.indexOf(a[randomNumber]) === -1 ) picked.push(a[randomNumber]);
        if ( picked.length < 3 ) 
           return picker(a, picked);
        else
           return picked;
    }
    

    游乐场:http://jsbin.com/owevuh/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2012-08-16
      • 1970-01-01
      相关资源
      最近更新 更多