数组类型
let arr = ['上海','北京','广州','深圳']
arr.sort((a, b) => a.localeCompare(b))
// sort()方法会改变原数组,localeCompare 需要和字符串搭配
console.log(arr) // ['北京', '广州', '上海', '深圳']
数组元素为对象类型
let arr = [
{EName:'sh',CName:'上海'},
{EName:'bj',CName:'北京'},
{EName:'gz',CName:'广东'},
{EName:'sz',CName:'深圳'}
]
// 根据EName值的首字母进行排序
arr.sort((a, b) => a['EName'].localeCompare(b['EName']))
console.log(arr)
/*
[{EName: 'bj', CName: '北京'},
{EName: 'gz', CName: '广东'},
{EName: 'sh', CName: '上海'},
{EName: 'sz', CName: '深圳'}]
*/
// 根据CName值的首字母进行排序
arr.sort((a, b) => a['CName'].localeCompare(b['CName']))
console.log(arr)
/*
[{EName: 'bj', CName: '北京'},
{EName: 'gz', CName: '广东'},
{EName: 'sh', CName: '上海'},
{EName: 'sz', CName: '深圳'}]
*/
相关文章:JS对字符串、数字或对象数组进行排序