Random but just in Chrome

后端 未结 3 363
轮回少年
轮回少年 2021-01-22 09:33

I\'ve this function to create a random range of numbers.

function randomRange(min, max) {
  return (new Array(++max-min))
  .join(\'.\').split(\'.\')
  .map(func         


        
3条回答
  •  故里飘歌
    2021-01-22 10:08

    This may due to the implementation of sort() method between explorers. From the fact that I've seen so far, I guess maybe the Chrome always use non-stable sort(e.g quicksort) when do sorting, while the others use stale sort(e.g bubble sort) when the input size is small.

    At first, the input(created originally from new Array(..)) is already sorted; and the function(){ return 0|Math.random()*max; } will always return a non-negative, which indicates that a>=b(or a<=b, I am not sure)? So, when I try to dig this out, I find that the sort behavior is different between Chrome and IE(version 9).

    In IE: [1,2,3].sort( function(){return 1} ) gives out [1,2,3]; but in Chrome, the result is [3,2,1], so I believe this maybe the real factor.

    So, as a conclusion, I would like to use .sort(function(){ return (0|Math.random()*max)-max/2; }) instead.

提交回复
热议问题