I am newbie to the javascript and I wrote the simple function below.
I am wonder that the function blow gave me the undefined. Is there any mistake in the function below?
function randFace() {
return ["crown", "anchor", "heart", "spade", "club", "diamond"]
[rand(0, 5)];
}
console.log(randFace())
Since it is not clear what is the
rand
in your problem does.Thus, in JavaScript, there is a function called random() that generates a random number between 0 and 1.
To generate the random index for the given array we need to have values between 0 and 6.
Since
Math.random
generated the value between 0 and 1, we need to multiply that value with thearr.length
.Undefined error is occurring because there is no rand() function. i believe that you want to get a random string from the array using the function. I have altered your code little bit to get the expected output. Try it to see if this is what you want
It is simple code using javscript
I think this is what you are looking for.:)
rand()
is an incorrect method in javascript.You will get your desired output by the following code.
You can refer more about random in W3 Schools.
Try this,