覆盖array.protype中的此值

Overwrite the this value in array.prototype

本文关键字:array protype 覆盖      更新时间:2023-09-26

我发现原生的js排序函数有时会出错,所以我想实现自己的函数。假设我有以下内容:

Array.prototype.customSort = function(sortFunction, updated) {...}
var array = [5, 2, 3, 6]
array.customSort(function(a,b) {return a - b})
console.log(array)

阵列应为[2,3,5,6]

Updated是已排序的数组。

无论我在customSort中返回什么,数组的顺序仍然是原来的顺序。如何覆盖"this"值/使其指向具有正确顺序的数组?

如果考虑上面给出的实际代码,则必须确保customSort函数更新this

一种情况是customSort只使用this作为"只读"输入,即-只将排序后的数组放在updated中,而不更改this。在这种情况下,考虑到上面的代码(您可能已经用它执行了测试),不会向函数发送updated参数来接收排序后的值。

另一种情况是customSort返回已排序的数组,在这种情况下,您必须收集它:

array = array.customSort(function(a,b) {return a - b});
console.log(array);

我刚刚迭代了updated数组,并用updated中的值替换了this中的每个值。在代码中,这看起来像。。。

function customSort(cb) {
    ...//updated is the sorted array that has been built
    var that = this;
    _.each(updated, function (ele, index) {
        that[index] = ele;
    })
}

我希望该函数的操作方式与本机array.sort函数完全相同——它覆盖所提供的数组,而不是返回一个新的排序数组。

我觉得这很奇怪。。。不能在一次干净的扫描中覆盖整个this值,但可以分步骤进行。我不能在customSort函数中这样做:

this = updated;