我试图像这样为 Array.prototype
定义一个随机化方法:
Array.prototype.randomize = function() { // Yes, this method does cause the array to have 'holes', but its good enough for this example/demonstration
var r = new Array(this.length); // Possible but somewhat unwanted to randomize the array in its place, therefore it has to be set to this new array later on.
this.forEach(function(e) {
r[Math.floor(Math.random() * r.length)] = e;
});
// how do I set 'this' to the variable r? (In order to change the array to the new and randomized array 'r')
return r;
}
此方法确实会返回随机数组,但我该如何更改数组本身呢?
最佳答案
正如评论所说,原地改变一个数组是一种更好的洗牌方式。
但是如果您确实需要一次性替换所有元素,您可以使用 Array#splice
:
Array.prototype.randomize = function() {
var r = /* the algorithm to get a replacement array... */;
this.splice(0, r.length, ...r);
return this;
}
...
是 spread operator .它是 ES2015 的一部分。
关于JavaScript array.prototype 如何将 'this' 设置为方法获取的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165446/