2014-09-27 27 views
0

我想從數組中獲得一個隨機數而不重複,但使用var newx = Math.floor(Math.random()* array.length);確實是隨機的,但是它的長度並不在數組內,所以它往往會重複。從JavaScript數組中挑選不重複的項目

<html> 
    <head> 

    </head> 
    <!-- <body> --> 
     <button onclick="myFunction()">Difficulty</button> 
     <p id="demo">here</p> 
     <p id="test"></p> 
     <script> 



function myFunction() { 

     function shuffle(o){ //try this shuffle function 
      for(var j, g, t = o.length; t; j = Math.floor(Math.random() * t), g = o[--t], o[t] = o[j], o[j] = g); 
      return o; 
     }; 

    var i; var l; var y; var n; 
    var newx; var newy; 
    var useranswer; var amountX; var largest; 
    var copyAmountX; 
    var mixAlot; 

    var x = parseInt(prompt("What is the first number?"+" "+"(up to 12)")); 

    if (x < 13) { 
     y = prompt("what is the second number?"+" "+"(choose up to 12)"); 
     n = prompt("how many problems to be solved?"); 
     amountX = [] 

     // adds to an array equal to x (user input) 
     if (!amountX.length) { 
     for (var s = 0; s <= x; s++) { 
      amountX.push(s); 
     } 
     }; 
     // just to let me know if it is working. Will be taken out. 
     alert(amountX); 
     largest = Math.max.apply(Math, amountX); 
     alert(largest); 
     alert(isNaN(x)); 
    } 
    else { 
     alert("Refresh page and restart with numbers under 12") 
    }; 
    if (y > 12 == true) { 
     alert("Refresh page and restart with numbers under 12") 
    }; 

    i = 0; 
    l = amountX.length; 
    copyAmountX = amountX; 
    // where the core magic of everything happens. 
    while (x < 13 && y < 13 && i<n) { 
     newx = shuffle(copyAmountX); 
     newy = Math.floor(Math.random() * y); 
     useranswer = prompt("Multiply "+newx+" by "+newy) 
     if (useranswer == newx * newy) { 
      alert("Correct! problem "+(i+1)+" of "+n); 
     }; 
     if (amountX == 0) {alert("You have completed your Difficulty! Good Game"); n = 0; 
     }; 
     i++; 
    }; 
}; 
</script> 


    </body> 
</html> 
+0

我會發布代碼,它會提示用戶。 – Hunter84 2014-09-27 22:11:26

回答

4

如果你想從數組中獲得隨機數,那麼我會建議不同的方法:複製陣列,並且洗牌副本。

function shuffle(o){ //try this shuffle function 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); 
    return o; 
}; 

這樣,你可以保持從混洗陣列彈出元素;他們將永遠是隨機的,只會發生一次。


現在你的代碼中,恐怕有很多的bug:...我刪除了這部分

修復:

我糾正你的程序和它的工作原理現在完美。請通過它並應用我在javascript中評論的更改。 Link

+0

我如何將這個添加到我的腳本? – Hunter84 2014-09-28 04:52:56

+0

請閱讀我剛剛添加的關於代碼中的錯誤的部分。 – zoran404 2014-09-28 11:29:41

+0

我更新了它,但現在不起作用。此外,我也經歷了codecademy.com上的javascript課程,並且目前正在teamtreehouse.com上工作。我正試圖完成所有事情。 – Hunter84 2014-09-28 18:50:58