Is it correct to use JavaScript Array.sort() method for shuffling?

前端 未结 12 1750
广开言路
广开言路 2020-11-22 03:48

I was helping somebody out with his JavaScript code and my eyes were caught by a section that looked like that:

function randOrd(){
  return (Math.round(Math         


        
12条回答
  •  梦如初夏
    2020-11-22 04:32

    There is nothing wrong with it.

    The function you pass to .sort() usually looks something like

    function sortingFunc( first, second )
    {
      // example:
      return first - second ;
    }
    

    Your job in sortingFunc is to return:

    • a negative number if first goes before second
    • a positive number if first should go after second
    • and 0 if they are completely equal

    The above sorting function puts things in order.

    If you return -'s and +'s randomly as what you have, you get a random ordering.

    Like in MySQL:

    SELECT * from table ORDER BY rand()
    

提交回复
热议问题