2015-12-29 26 views
0

我發現原生js排序函數時常出現問題,所以我想實現我自己的。可以說我有以下內容:覆蓋array.prototype中的這個值

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]

更新是已排序的數組。

無論我在customSort中返回什麼,數組的順序仍然是原始順序。我如何覆蓋'this'值並使其指向正確的順序?

+0

你是什麼意思呢? '[5,2,3,6] .sort(function(a,b){return a - b;})'每次都很完美。 – Andy

+0

我並不是故意在這種情況下說出來。我發現它沒有正確排序的情況。我試圖給出一個非常簡單的例子,我想要一個customSort函數返回。我認爲在這一點上我非常清楚。 – user3619165

+0

爲什麼不給實際的例子失敗呢? – Andy

回答

0

我剛剛結束了遍歷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; 
0

如果您考慮上面給出的實際代碼,您必須確保您的customSort函數更新this

一種情況是customSort僅使用this爲「只讀」輸入,那就是 - 僅把排序後的數組中updated,而不是改變this。 在這種情況下,考慮上面的代碼(您可能已經執行了測試),沒有updated參數被髮送到該函數,以接收排序的值。

另一種情況是customSort返回數組排序,在這種情況下,你必須收集它:

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