【问题标题】:Javascript array shuffleJavascript数组洗牌
【发布时间】: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


【解决方案1】:

因为你要给Array.prototype添加一个可枚举属性(shuffle),如果你坚持用for-in迭代,你需要添加一个hasOwnProperty测试:

Array.prototype.shuffle = function () {
    for (var i in this) {
        if ( this.hasOwnProperty(i) ) {
           var j = Math.floor(Math.random() * this.length);
           this[i] = this[j] + (this[j] = this[i], 0);
        }
    }

    return this;
};

否则我宁愿建议:

Array.prototype.shuffle = function () {
    for (var i=0; i < this.length; i++) {
        var j = Math.floor(Math.random() * this.length);
        this[i] = this[j] + (this[j] = this[i], 0);
    }

    return this;
}

http://jsfiddle.net/2m5q3d2j/5/

您还可以在 ES5+ 引擎上使用 Object.defineProperty 创建属性,以避免使其可枚举。

【讨论】:

  • 几秒钟后我开始踢自己了。 @LiNoimiSemain:这就是为什么你不使用for-in 来循环数组,有更好的方法没有这个问题。
  • 那么使用for (var i = 0; i &lt; this.length; i++)比较好?
  • @LiNoimiSemain:阅读我给你的链接。
猜你喜欢
  • 2013-06-28
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2019-02-07
  • 1970-01-01
相关资源
最近更新 更多