javascript - How "Math.random() * arr.length | 0" works for return a random index for an array -


i've been working in legacy code have functionality should return random item array , see following expression:

array[math.random() * arr.length | 0] 

my first impression try undestand the | operator can't figure out how work. test expression in chrome console , see returns valid index this:

let array = [1,2,3,4] for(let = 0; < 5000; i++){    console.log(array[math.random() * arr.length | 0]); } 

how "math.random() * arr.length | 0" works return random index array?

  • math.random() returns number >= 0 , < 1.
  • * arr.length returns number >= 0 , < arr.length, yet can't used index, because have fractional part
  • | 0 coerces left expression integral number applies bitwise or number zero, other number

this said, makes work implicit conversion (called coersion) in operator |.


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -