【发布时间】:2014-11-29 12:45:37
【问题描述】:
当我在 javascript 中对数组进行洗牌时遇到了这个奇怪的问题,但我不知道是什么问题。有人可以帮帮我吗?
当我像这样洗牌时
[1,2,3,4,5,6,7,8,9,10]
我得到一个空值,像这样
[null,10,1,8,9,3,2,7,6,4]
这是代码(http://jsfiddle.net/2m5q3d2j/):
Array.prototype.suffle = function () {
for (var i in this) {
var j = Math.floor(Math.random() * this.length);
this[i] = this[j] + (this[j] = this[i], 0);
}
return this;
};
【问题讨论】:
-
嗯,第一件事是,不要使用
for-in循环遍历数组(没有安全措施,还有更好的方法)。更多:stackoverflow.com/questions/9329446/… -
这不是问题,但以这样的评价顺序玩游戏完全没有必要。使用翻转的临时变量。
-
@T.J.Crowder:您要查找的链接是stackoverflow.com/questions/500504/… :-)
-
@Bergi:我认为我上面的回答解决了这些问题,甚至更多。 :-)
标签: javascript arrays random shuffle