Math.random() function generates a random number between 0 and 1 (with more or less digits decimals - usually 16).
To obtain a random weighed number between 0 and N you simply multiply the genuine random number with the difference (N-0) and round the result
To round you may use different functions such as
Math.round - automatic
Math.floor - rounds down
Math.ceil - rounds up
It looks like using Math.floor or Math.ceil is a better choise than Math.round (they give a "more randomized" weighed numbers). Math.floor has another advantage, see below.
In your example, you need to obtain a random weighed number between 0 and the lenght of your object type (the number of the objects). Why not lenght-1?... Becouse Math.floor will round for instance 2.99999999999 as 2, and never reach the full 3.
So here we are with the explanation for the fredmv's code