随机但只是在Chrome中 [英] Random but just in Chrome
问题描述
我有这个功能来创建一个随机数字范围。
I've this function to create a random range of numbers.
function randomRange(min, max) {
return (new Array(++max-min))
.join('.').split('.')
.map(function(v,i){ return min+i; })
.sort(function(){ return 0|Math.random()*max; });
}
它完美但仅限Chrome。所有其他浏览器由于某种原因变化很小...
It works perfect but only in Chrome. All other browsers have very little variation for some reason...
我在这里有一个简单的演示,所以你可以看到差异 http://jsfiddle.net/elclanrs/zZRda/ 。
I've a simple demo here so you can see the difference http://jsfiddle.net/elclanrs/zZRda/.
尽可能看到Chrome中的数字顺序大多是随机的,但在其他浏览器中没有太多变化,只有少数数字会改变,但它们看起来几乎相同。
As you can see the order of numbers in Chrome is mostly random but in other browsers there's not much variation, only a few numbers change place but it all looks almost the same.
现在检查在Chrome和其他浏览器中 http://jsbin.com/iyalax/3/edit 我会非常清楚地看到差异。
Now check http://jsbin.com/iyalax/3/edit in Chrome and other browsers and you'll see the difference very clearly.
为什么会发生这种情况?
Any ideas why this is happening?
编辑:我还有另一个 randomRange
函数在所有浏览器中运行正常,它只是更长且更丑,请检查 http://jsbin.com/iyalax/4/edit 以查看差异。
I've another randomRange
function that works fine in all browsers, it's just longer and uglier, check http://jsbin.com/iyalax/4/edit to see the difference.
推荐答案
问题解决了!我在Hacker News找到了一个非常好的解决方案,它现在在所有浏览器中都很完美:
Problem solved! I found a pretty sweet solution at Hacker News, it works perfect in all browsers now:
function randomRange(min, max) {
return (new Array(++max-min))
.join('.').split('.')
.map(function(v,i){ return min+i; })
.map(function(v) { return [Math.random(), v]; })
.sort().map(function(v) { return v[1]; });
}
演示: http://jsbin.com/iyalax/9/edit (如果看不到图像,请点击用JS运行 )
Demo: http://jsbin.com/iyalax/9/edit (click "Run with JS" if you can't see the image)
这篇关于随机但只是在Chrome中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!