JavaScript array.prototype 如何将 'this' 设置为方法获取的新数组

标签 javascript arrays this

我试图像这样为 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 的一部分。

Spread operator compatibility table

关于JavaScript array.prototype 如何将 'this' 设置为方法获取的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165446/

相关文章:

javascript - 在 JavaScript 中解构对象时如何绑定(bind)方法?

javascript - 在连接时加入套接字 io 房间

java - 将一行的特定部分添加到数组中

c# - 反转多维数组中元素的顺序

javascript - Jquery 每次替换innerHtml

javascript - JavaScript中的this关键字问题

javascript - 无效的正则表达式 JavaScript

javascript - React 事件处理程序中的 event.target null

javascript - 即使返回结果,AnuglarJS 中的结果也未定义

Javascript 的 forEach() 方法创建具有未定义键的数组