Math.random array length +1?
I don't understand something in this code :
vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))];
Let's say we have a new Array
, with 5 elements, so from index 0 to index 4
Then let's say Math.random()
returns 1. So, we've got the floor of 1*5
, but the 5 index doesn't exist in my Array
, plus here we add a "+1"
Why +1? I would have expected exactly the opposite with "-1".
The code is wrong (as Rocket said). It should be
Math.floor(Math.random()*(anims.length))
But also the reasoning has a flaw : Math.random() cannot return "1".
Math.random
does not return 1, it returns a value from 0 to 1. Math.floor
basically truncates the decimal off of the value.
So, if Math.random
returns 0.3984753005206585
and multiply it by 4
we get 1.593901202082634
which becomes 1
after Math.floor
.
When you want to get a random value from an array, you multiply Math.random
by the length, so it will return values between 0 and the length (but never the length).
The anims.length + 1
is incorrect in the above code.
精彩评论