0

I'm trying to wring a script that outputs an array and counts the number of elements in the array based on user input.

<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
  • 2
    That's not Java (and you forgot the language tag anyway). Also you didn't ask an actual question or explain what's wrong with this code Commented Jun 13, 2017 at 19:51
  • And what's the question? P.S. <!-- ... --> - wrong comments for JavaScript Commented Jun 13, 2017 at 20:08

2 Answers 2

1

Please don't forget to ask an actual question. Assuming you're asking to make your script work, this should do the trick.

    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.
Sign up to request clarification or add additional context in comments.

Comments

0

a couple of things. first, your function doesnt actually cycle through the array, so it cant actually search the for the target value. if you want to get a value out of a function, you need to return that value inside the function

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.