2011-05-03 33 views
1

刪除的元素可能重複:
How to remove first element of an array in javascript?從陣列中的Javascript

function write() { 
    for (var x = 1; x <= 3; x++) { 
     var question = new Array("If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6"); 

     var l = question.length; 

     var rnd = Math.floor(l * Math.random()); 

     document.write(question[rnd]); 
     document.write("<br>") 
    } 

} 

這是我的代碼,但它輸出相同的問題(字符串)有時當我想要的三個問題是不一致的,在輸出後如何從數組中移除一個元素?

回答

1

你可以試試:

question.splice(rnd,1) 

在你的循環結束將這個,它會刪除剛剛顯示的元素。

0

而不是從數組中刪除一個元素,你可以跟蹤你已經使用的隨機索引,並避免它們。事情是這樣的:

function write() { 
    for (var x = 1; x <= 3; x++) { 
    var question = new Array(...); 
    var used={}, l=question.length, rnd; 
    do { 
     rnd = Math.floor(l * Math.random()); 
    } while (rnd in used); 
    used[rnd] = true; 
    document.write(question[rnd]); 
    document.write("<br>") 
    } 
} 
3

你需要使用數組的splice()方法。但是,每次迭代都會創建一個新數組,因此您需要將該部分移出循環。

function write() { 
    var questions = [ 
     "If you are goofy which is your leading foot", 
     "Riding switch is when you do what", 
     "On your toe side which way should you lean", 
     "question 4", 
     "question 5", 
     "question 6" 
    ]; 

    for (var x = 1; x <= 3; x++) { 
     var rnd = Math.floor(questions.length * Math.random()); 
     document.write(questions[rnd] + "<br>"); 
     questions.splice(rnd, 1); 
    } 
} 
0

我同意蒂姆的迴應。此外,雖然,你可以做這樣的壓縮代碼多一點點:

function write() { 
    var question = ["If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6"]; 

    for (var x = 1; x <= 3; x++) { 
    var rnd = Math.floor(question.length * Math.random()); 
    document.write(question.splice(rnd, 1)[0] + "<br>"); 
    } 
} 

原因上面的代碼也將工作是因爲接頭不僅能消除元素,但也返回子被刪除的數組。

+0

如果您是編寫長行代碼的忠實粉絲,您甚至可以將隨機數生成移動到拼接函數第一個參數的位置。 – 2011-05-03 16:13:30