2017-06-13 68 views
-1

我試圖擰一個腳本,輸出一個數組並根據用戶輸入計算數組中元素的數量。JavaScript計數函數

<script> 
    // Function searches a given array and counts the number of times an element appears in the array. 
    function countOccurences(numArray, num) // function 
     {       //parameters 
      var count = 0; 

      if(array[i] == 2) 
      count++; 
     } 
</script> 
</head> 
<body> 
<script> 
var num = [2, 6, 33, 1, 77, 2, 98]; <!-- array --> 
document.write("<p>"+nums.toString()+"</p>"); <!-- fill the array--> 
var count = parseFloat(prompt("Please enter number to search for", "")); <!--ask for the numer to search --> 
// linear search 
var p = countOccurences(nums, key) ; 

document.write("<p>Value "+p+" was not found in array </p>"); //output the count 

</script> 

</body> 
</html> 
+2

這不是Java(而且你總是忘記語言標記)。你也沒有問過一個實際的問題或解釋這個代碼有什麼問題 – UnholySheep

+0

這是什麼問題?附: '' - JavaScript的錯誤評論 – FieryCat

回答

0

幾件事情。首先,你的函數實際上並不循環數組,所以它實際上無法搜索目標值。如果你想從函數中獲得一個值,你需要返回函數內部的值

<script> 
    function countOccurences(numArray, num) 
     {       
      var count = 0; 
      for (let i = 0; i < numArray.length; i++ ){ 
       if (numArray[i] == target) count++ 
      } 
      return count 
     } 
</script> 
1

請不要忘記問一個實際的問題。假設你要讓你的腳本工作,這應該會有訣竅。

function countOccurences(numsArr, target){ 
     let count = 0; 
     for (let i = 0; i < numsArr.length; i++ ){ 
      if (numsArr[i] == target) count++ 
     } 
     return count; 
    } 
    const nums = [2, 6, 33, 1, 77, 2, 98]; 
    const target = parseFloat(prompt("Please enter number to search for", "")) 
    const count = countOccurences(nums, target) // you can output count in whatever way you like.