2017-06-20 72 views
-2

有很多關於排序的例子,但我無法理解任何人。任何人都可以幫助按鈕點擊時切換排序。如何在JavaScript中切換排序?

<button onclick="sortName()">Sort</button> 

var contacts= [ 
{ 
    "id": 1, 
    "name": "xyz", 
    "email": "[email protected]", 
    "phone": "0000958331" 
}, 
{ 
    "id": 2, 
    "name": "abc", 
    "email": "[email protected]", 
    "phone": "0110958332" 
}, 
{ 
    "id": 3, 
    "name": "efg", 
    "email": "[email protected]", 
    "phone": "0220958333" 
} 
] 

function sortName(){ 
contacts.sort(function (a, b) { 
const x = a.name.toLowerCase(); 
const y = b.name.toLowerCase(); 
return (x < y ? -1 : x > y ? 1 : 0); 
}); 

console.log(contacts); 
} 

鏈接:https://codepen.io/sarash/pen/PjpLdd?editors=1010

+0

你有問題嗎?你會更明確地回答你的具體情況。你的問題是這段代碼似乎不起作用? –

+0

此代碼的工作原理,但我不知道如何使它切換,所以當按鈕被點擊時第二次名稱應按降序出現,等等。 – srs

+0

你可以看看'localeCompare'方法來比較兩個字符串,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare – kas

回答

0

要使其切換,你可以把一個變量調用函數外部存儲當前的訂單和切換它的每次點擊:

var order = false; 
var contacts= [ 
{ 
    "id": 1, 
    "name": "xyz", 
    "email": "[email protected]", 
    "phone": "0000958331" 
}, 
{ 
    "id": 2, 
    "name": "abc", 
    "email": "[email protected]", 
    "phone": "0110958332" 
}, 
{ 
    "id": 3, 
    "name": "efg", 
    "email": "[email protected]", 
    "phone": "0220958333" 
} 
] 

function sortName(){ 
    order = !order; 
    contacts.sort(function (a, b) { 
    const x = a.name.toLowerCase(); 
    const y = b.name.toLowerCase(); 
    return (order ? x > y : x < y); 
    }); 
    console.log(contacts); 
} 
+0

它剛剛顯示從上升到下降,但我希望名稱出現從下降到升也當第二次點擊按鈕 – srs

+0

我改變了代碼,並添加'訂單'作爲開關狀態。 – Alinex

+0

感謝Alinex,這就是我一直在尋找的。你是唯一瞭解我的問題的人。 – srs