Currently, I am utilizing JavaScript to define the background image of an element through a class. The majority of the code works flawlessly, however when I execute it, I encounter an undefined variable error. To obtain the numbers for the variables, I have employed Math.Random(). The specific issue lies within this section of my code (or at least that's what I believe):
var RandomContentDiv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
var cd = RandomContentDiv[Math.round(Math.random()*RandomContentDiv.length-1)];
console.log(cd);
I included console.log(cd);
in order to observe the outputted numbers. Although results are generated, they do not assist in troubleshooting the problem. To provide some insight, I will run the code twice and share the typical outcomes with you.
Test 1:
Number: 5
Number: 13
Number: 10
... (list of numbers continues)
Number: 8
Number: 6
Number: 1
Number: 11
Number: 12
Number: 0
Number: 6
Number: 8
Number: 1
Number: 11
Number: 1
Number: 12
Number: undefined
Test 2:
Number: 13
Number: 2
Number: 9
... (list of numbers continues)
Number: 0
Number: undefined
My assumption is that the issue stems from the statement:
RandomContentDiv[Math.round(Math.random()*RandomContentDiv.length-1)];
. However, due to my lack of extensive knowledge on Math
in JavaScript, I am uncertain how to rectify it. All I know is that there may be concerns regarding the accuracy of Math.Round
when used for rounding off numbers (e.g. 1.5 being rounded down to 1). If anyone can confirm whether it is indeed the statement causing the error or if there is another factor at play, I would greatly appreciate the assistance.