2012-12-22 61 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解釋它是如何工作的。)