Click here to Skip to main content
15,843,727 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created 2 functions, with the RepeatNtimes() supposed to display the DOM elements results and call the CountIndex() inside. While the CountIndex() has to access the input.value and generate random number by the "input" times. If I consoled the code below it can't undefined the element arr[j] and also skipped the loop in the CountIndex(). It's nothing change when I switch the string literal from the RepeatNtimes() to the CountIndex()

        let arr = [0,0,0,0,0,0,0,0,0,0];
        //input number DOM object
        let input = document.querySelector("#input_number");
        let num = Number(input.value); 
        function RepeatNtimes() 
           for(let i =0; i<=num;i++)
               // Clear array
               arr = [];
         function CountIndex()
          for(let j = 0;j<=num;j++)
          let rand = Math.floor(Math.random()*10);
    document.querySelector("#re").innerHTML = `${j} appearance is: ${arr[j]} <br>`;

What I have tried:

I use that string literals instead of declare 10 DOM object from 0-9
Updated 16-Jul-21 4:27am

1 solution

You haven't shown how your functions are being called. But it's suspicious that you've declared your num variable outside of any function. Its value will be assigned as soon as the page loads, so unless your input already contains a valid number, the num variable isn't going to contain what you expect.

Move the declaration inside the RepeatNtimes function, and pass it as a parameter to your CountIndex function.
Share this answer
Member 14629414 16-Jul-21 13:12pm    
Richard Deeming I'm building a program which display the frequency of each number from 0 to 9 when generate random (0,9) a certain times(num) and that "num" used by both 2 functions so I declared it globally. Nothing change when I move it inside RepeatNtimes() and pass it as parameters in CountIndex(). Incase you have no idea about what I'm aiming for.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900