2015-12-06 32 views
0

爲了使這相當簡單,我在代碼中的評論說明我正在努力完成。我的代碼執行似乎不會繼續計算,直到它找到一個空類的.wrap,這正是我想要做的。也許有人可以幫我弄清楚如何擴展無限檢查,最終找到一個未定義類的open .wrap。JavaScript隨機數尋找hasClass,不存在

function computerMove(){ 
    //returns number between 1-9 
    var rand = Math.floor((Math.random() * 9) + 1); 
    console.log(rand); 

    //checks for if .wrap has class of x and if it does it should get another number 
    var check = $(".board .wrap:nth-child("+rand+")").hasClass("x"); 


    if(check){ 
    console.log("checking") 
    var rand = Math.floor((Math.random() * 9) + 1); 
    //I believe this should work and repeat the function 
    computerMove(); 
    } 
    else{ 
    $(".board .wrap:nth-child("+rand+")").addClass("o"); 
} 
+0

你是一個循環中運行這個或者這是所有的代碼? –

+0

@NickKenens它是遞歸函數。 – jcubic

+0

@jcubic打字後我注意到了,我的不好。如果沒有給出任何參數,使用循環遞歸函數有什麼好處?對我來說似乎有點野蠻。 –

回答

1

不,不必在不需要時使用遞歸函數。使用循環。

function computerMove(){ 
    var check; 
    var rand; 
    do { 
     //returns number between 1-9 
     rand = Math.floor((Math.random() * 9) + 1); 
     console.log(rand); 
     check = $(".board .wrap:nth-child("+rand+")").hasClass("x"); 
    } while (check) 

    $(".board .wrap:nth-child("+rand+")").addClass("o"); 
} 

或者它可能是簡單的「智能」地使用jQuery選擇

// Find all elements that do not have x class 
var items = $(".board .wrap:not(.x)") 
// Get a random element 
var target = items[Math.floor(Math.random()*items.length)]; 
// Add o class to the target 
$(target).addClass('o')