[英]Javascript array 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;
};
因為您要向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/
您還可以使用Object.defineProperty
在ES5 +引擎上創建該屬性,以避免將其枚舉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.