Javascript数组随机播放

时间:2014-11-29 12:45:38

标签: javascript arrays random shuffle

当我在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;
};

1 个答案:

答案 0 :(得分:4)

因为您要向shuffle添加可枚举属性(Array.prototype),如果您坚持使用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/

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

相关问题