How does this W3Schools code for shuffling an array with .sort() work?

前端 未结 2 1157
无人共我
无人共我 2021-01-21 19:34

This code snippet is from w3schools JavaScript section. I am trying to figure out what

points.sort( function(a, b) {
  return 0.5 - Math.random()
});

2条回答
  •  离开以前
    2021-01-21 19:46

    The sort callback is supposed to return a value <0, 0 or >0 to indicate whether the first value is lower than, equal to or higher than the second; sort uses that to sort the values. 0.5 - Math.random() returns a value between -0.5 and 0.5 randomly, satisfying the expected return values and resulting in an essentially randomly shuffled array.

    Note that this shouldn't be the preferred method to shuffle; since the return value is random and not internally consistent (e.g. it tells sort that foo < bar, bar < baz and foo > baz), it may make Javascript's sort algorithm very inefficient. A Fisher-Yates shuffle for instance is pretty trivially implemented and likely more efficient.

提交回复
热议问题