2017-02-26 9 views
-1
function compare(a, b) { 
    if (a is less than b by some ordering criterion) { 
    // how minus 1 will affect to sort? how sort will understand this value? 
return -1; 
    } 
    if (a is greater than b by the ordering criterion) { 
    return 1; 
    } 
    // a must be equal to b 
    return 0; 
} 

或在下面的例子中是如何影響:我無法理解「迴歸」價值排序

var numbers = [4, 2, 5, 1, 3]; 
numbers.sort(function(a, b) { 
    return a - b; 
}); 
console.log(numbers); 

// [1, 2, 3, 4, 5] 

我知道只知道「真」或「假」,這是1和0。如何比較和排序將明白什麼是(1,-1,0),以及如何使用這些值進行排列?

+0

重複的http://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function – yakobom

+2

可能的重複[如何排序函數在JavaScript中工作,以及比較函數](http://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function) – SOFe

回答

0

documentation at MDN描述這個很好:

arr.sort(的compareFunction)

如果的compareFunction被提供時,所述陣列元件根據比較函數的返回值排序 。如果a和b是 兩個元件被比較,則:

  • 如果的compareFunction(A,B)小於0,排序一個比B,即一個較低折射率的第一。
  • 如果compareFunction(a,b)返回0,則相對於彼此保持a和b不變,但相對於所有的 不同的元素進行排序。注意:ECMAscript標準不保證此行爲,因此並非所有瀏覽器(例如,至少可以追溯到2003年的Mozilla
    版本)都尊重這一點。
  • 如果compareFunction(a,b)大於0,則將b排序爲比a更低的索引。當給定一對特定元素a和b作爲其兩個參數 時,compareFunction(a,b)必須始終返回相同的 值。如果返回不一致的結果,則排序順序 未定義。
+0

謝謝,它真的幫助我 – Dos

1

Array.prototype.sort函數期望回調返回一個數,而不是一個布爾(例如,不truefalse)。它使用數字來知道它給排序回調的兩個條目的順序應該是什麼。您可以在sort想象的邏輯沿着這些路線是:

result = callback(a, b); 
if (result < 0) { 
    // Make sure `a` is before `b` 
} else if (result > 0) { 
    // Make sure `b` is before `a` 
} else { 
    // It doesn't matter which is first, they're equivalent 
} 

正如你所看到的,truefalse不參與(除的<>的結果)。

這意味着,如果ab是數字和回調返回a - b,它將數字排序,因爲如果a小於b,結果將是負的;如果a大於b,則結果爲正;如果它們相同,則結果爲0