覆盖array.protype中的此值
Overwrite the this value in array.prototype
我发现原生的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;
相关文章:
- 如何为json对象中的段发送array[]
- Array.length似乎不起作用;console.log则显示其他情况
- 如何迭代Array.prototype函数
- Javascript 新的 Array 和 join() 方法
- Array.lenght = undefined
- Javascript setTimeout for an array
- NodeJS API调用中Array中的Push和Pull元素
- 如何在MongoDB中将String转换为Array
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- 您的平台不支持RxJS-Array.observe
- 在Jquery/Javascript中的Array中插入Textbox值
- 通过jQueryAjax一起发布Array和Form数据时出现问题
- Array.every返回false,而不是类型error
- Javascript-通过i=0直接传递array[0]与array[0],array[i]在“;如果“;陈述
- JavaScript Array unshift() 以一种不可变的方式
- 为什么可以't我用Set对象调用Array.prototype.map
- Array.protype.every()-获取falsy值元素
- 覆盖array.protype中的此值
- 为什么Ractive.js reset()和update()方法重复模板,因为有一个带有array.protype.so
- 在字符串上实现array.protype.reduce()