2012-12-22 59 views
2

平凡的问题。我到目前为止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()) 

    }); 
}); 

我已经看到了使用拼接方法类似的问题,我试图破解版本一起,但我想知道是否有更有效的方法。

+0

告诉你试图拼接代码。方法可能是更简单的解决方案之一。 WOuld还需要检查数组是否具有长度,如果所有名称都用完,则执行一些不同的操作 – charlietfl

回答

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/

0

您可以改为随机洗牌手前阵,然后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解释它是如何工作的。)