有很多关于排序的例子,但我无法理解任何人。任何人都可以帮助按钮点击时切换排序。如何在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