+ 2
The first item in the colors sequence is never found for the fuction pickRandom but I don't know why.
if anyone knows please explain and fix the code for me to know what is the right way to do it. var colors = [ "red", "green", "blue", "yellow", "purple", "coral", "gold", "white", "black", "brown", "pink" ]; function pickRandom(aList){ return aList[Math.ceil(Math.random() * 10)] }; console.log(colors[Math.ceil(Math.random() * 10)]); document.write(pickRandom(colors)) The code: https://code.sololearn.com/WNHrflhXY2Sy/?ref=app
3 RĂ©ponses
+ 2
Math.ceil rounds up to the nearest whole number(closest to +â). Math.ceil(Math.random()*10) won't(almost impossible) return 0.
To get a random array element:
arr[ Math.floor(Math.random()*arr.length)] is commonly used.
+ 3
You ceil, so round up. Giving you numbers between 1 and 10. 0 is never reached.
Instead use...
Math.floor(Math.random()*colors.length)
+ 3
Thank you guys, I can get it now