【问题标题】:Randomly select value form array and delete this value from array从数组中随机选择值并从数组中删除该值
【发布时间】:2012-12-09 23:57:36
【问题描述】:

琐碎的问题。到目前为止我有什么http://jsfiddle.net/Dth2y/1/

任务,下一个按钮应该从数组中随机选择一个值并从数组中删除该值。到目前为止,这称为 getNames 函数,在此函数中,从数组中随机选择的值在附加到 html 后也应该被删除。

HTML

<h1 id="name">Click Next To Start</h1> <button id="next">NEXT NAME</button> <button>SKIP NAME</button>

JS

     $(document).ready(function() {
     var names = [
         "Paul",
         "Louise",
         "Adam",
         "Lewis",
         "Rachel"
     ];

     function getNames() {
        return names[Math.floor(Math.random() * names.length)];

     }

             $("#next").click(function() {
                 $('#name').text(getNames())

     });
 });

我在使用 splice 方法时看到过类似的问题,我曾尝试将一个版本一起破解,但想知道是否有更有效的方法。

【问题讨论】:

  • 显示您尝试的拼接代码。方法可能是更简单的解决方案之一。还需要检查数组是否有长度,如果所有名称都用完,则做一些不同的事情

标签: jquery arrays random


【解决方案1】:

您可以改为随机随机打乱数组,然后pop() 第一个元素或shift() 最后一个元素。

/**
 * Shuffles an array in-place
 */
function shuffle(array) {
    for (var i = array.length-1; i > 0; --i) {
        // Select a random index 0 <= j <= i
        var j = Math.floor(Math.random() * (i+1));
        // Swap elements at i and j
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

$(document).ready(function() {
    var names = [
        "Paul",
        "Louise",
        "Adam",
        "Lewis",
        "Rachel"
    ];

    // Shuffle the names
    shuffle(names);

    $("#next").click(function() {
        // Grab the next name and remove it
        $('#name').text(names.pop());
    });
});

shuffle 函数基于 the Fisher-Yates shuffle algoritmThis post 解释了它的工作原理。)

【讨论】:

    【解决方案2】:

    你会想看看这个:http://ejohn.org/blog/javascript-array-remove/

    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };
    

    这里它适用于您的小提琴: http://jsfiddle.net/Dth2y/3/

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多