Javascript数组洗牌

Javascript数组洗牌,javascript,arrays,random,shuffle,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] 这是代码(): 因为您正在将可枚举属性(shuffle)添加到Array.prototype,如果您坚持在中使用进行迭代,则需要添加hasOwnProperty测试: Array.prototype.shuffle = function () { fo

我在javascript中洗牌数组时遇到了一个奇怪的问题,我不知道问题出在哪里。有人能帮我吗

当我洗牌这样的数组时

[1,2,3,4,5,6,7,8,9,10]

我得到一个空值,如下所示

[null,10,1,8,9,3,2,7,6,4]

这是代码():


因为您正在将可枚举属性(
shuffle
)添加到
Array.prototype
,如果您坚持在中使用
进行迭代,则需要添加
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;
}
Array.prototype.shuffle=函数(){
for(var i=0;i


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

因为您正在将可枚举属性(
shuffle
)添加到
数组中。prototype
,如果您坚持在
中使用
进行迭代,则需要添加
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;
}
Array.prototype.shuffle=函数(){
for(var i=0;i


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

首先,不要使用
for in
在数组中循环(没有安全措施,还有更好的方法)。更多:这不是问题所在,但是用这样的评估顺序玩游戏完全没有必要。使用flippin'temp变量。@T.J.Crowder:您要查找的链接是:-)@Bergi:我想我上面的答案解决了这些问题,还有更多问题。:-)首先,不要使用
for in
在数组中循环(没有安全措施,还有更好的方法)。更多:这不是问题所在,但是用这样的评估顺序玩游戏完全没有必要。使用flippin'temp变量。@T.J.Crowder:您要查找的链接是:-)@Bergi:我想我上面的答案解决了这些问题,还有更多问题。:-)几秒钟后我就开始踢自己了@LiNoimiSemain:这就是为什么你不使用
for in
来循环数组,有更好的方法可以避免这个问题。所以使用
for(var i=0;i
更好吗?@LiNoimiSemain:阅读我给你的链接。几秒钟后我踢了自己@LiNoimiSemain:这就是为什么你不使用
for in
来循环数组,有更好的方法没有这个问题。所以使用
for(var i=0;i
更好?@LiNoimiSemain:阅读我给你的链接。