2016-01-06 79 views
-2

所以我試圖找出從零到十的每個數字中有多少是隨機數組中生成的。 我創建了一個隨機數組列表計數隨機數組中的數字

i=0; 
    var ranList=[]; 
    while (i<20){ 
     i++; 
     ranList.push(Math.floor(10*Math.random())); 
    } 
    //count each number 
    document.write(ranList.sort().join("<br>")); 

/*Then I made a function to count /elements from this array 
*/ 


    function ctnumber(array,elem){ 
     var ct=0; 
     var j =0; 
     while(j<array.length) 
     { 
     j++; 
      if(array[j]==elem){ 
      ct+=1;} 
     } 
     } 
     return ct; 
     } 
     alert(ctnumber(ranList,5)); 

第二個函數不執行,任何想法,爲什麼?

謝謝!

+1

如果您清理了一下代碼並顯示代碼,可能會有所幫助,而不是像兩個代碼片段。 – JosephGarrone

+0

好吧,我現在要做 – Kepazino

+0

「不執行」?!就像*一樣*?!我們無法告訴您爲什麼這是基於您展示的內容。 – deceze

回答

1

首先,你應該避免使用名稱數組變量你: http://www.w3schools.com/js/js_reserved.asp

你的括號也是錯誤的。改變你的函數這一點,它應該工作:

function ctnumber(arr,elem){ 
     var ct=0; 
     var j =0; 
     while(j<arr.length) 
     { 
     j++; 
      if(arr[j]==elem){ 
      ct+=1;} 
     } 
     return ct; 
     } 
+2

這不回答這個問題,將作爲評論更好地發揮。 – JosephGarrone

+0

@JosephGarrone謝謝。我改變了答案。 – apxp

+0

謝謝,解決了它。出於某種原因,數組沒有作爲一個變量給出麻煩,也許是因爲它在lowercaps ... – Kepazino

1

的問題與您的代碼,在他的評論被Pardeep說,是你在你的第二個while迴路有一個額外的}ct+=1;後。

正確的代碼是:Fiddle

i = 0; 
var ranList = []; 
while (i < 20) { 
    i++; 
    ranList.push(Math.floor(10 * Math.random())); 
} 
//count each number 
document.write(ranList.sort().join("<br>")); 

function ctnumber(array, elem) { 
    var ct = 0; 
    var j = 0; 
    while (j < array.length) { 
    j++; 
    if (array[j] == elem) { 
     ct += 1; // NOTE NO } HERE NOW 
    } 
    } 
    return ct; 
} 
alert(ctnumber(ranList, 5)); 

我也建議有點代碼清理:

var i = 0; 
var ranList = []; 
while (i < 20) { 
    i++; 
    ranList.push(Math.floor(10 * Math.random()); 
} 

function countNumbers(list, elem) { 
    var count = 0; 
    // For loops are generally more readable for looping through existing lists 
    for (var i = 0; i < list.length; i++) { 
     if (list[i] == elem) { 
      count++; 
     } 
    } 
    return count; 
} 
alert(countNumber(ranList, 5)); 

請注意console.log()是一個更好的調試工具,它可以訪問通過Firefox和Chrome/IE中的F12

+0

謝謝我' m使用android應用程序輔助Web代碼,我會找出如何在其中使用控制檯 – Kepazino