有很多關於排序的例子,但我無法理解任何人。任何人都可以幫助按鈕點擊時切換排序。如何在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
你有問題嗎?你會更明確地回答你的具體情況。你的問題是這段代碼似乎不起作用? –
此代碼的工作原理,但我不知道如何使它切換,所以當按鈕被點擊時第二次名稱應按降序出現,等等。 – srs
你可以看看'localeCompare'方法來比較兩個字符串,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare – kas