qq_笑_17
兄弟,你的obj写法有问题吧;正常的对象写法应该 {key: value}吧;你哪种应该是数组比较合适var obj=['a','baaa','aba','a','aaaaa']排序思路获取obj的key数组对key进行排序更具key赋值到新的obj上代码function ksort(arr) { if (arr.length <= 1) { return arr; } const pivotIndex=Math.floor(arr.length / 2); const pivot = arr.splice(pivotIndex, 1)[0]; const pivotLength = pivot.match(/a/ig).length let left = []; let right = []; for (let i = 0; i < arr.length; i++) { if(arr[i].match(/a/ig).length <= pivotLength){ right.push(arr[i]); } else { left.push(arr[i]); } } return ksort(left).concat([pivot], ksort(right));}function sortObj(obj){ if (obj instanceof Array) { return ksort(obj); } else { let arrList = Object.keys(obj); const sortList = ksort(arrList); let newObj = {}; sortList.forEach((value) => { newObj[value] = obj[value] }) return newObj; } }例子//obj是对象let obj = {aaaaa: 1, baaa: 2, aba: 3, a: 4, aaaaaaaaaaaaa: 5}obj = sortObj(obj)/***结果*{aaaaaaaaaaaaa: 5, aaaaa: 1, baaa: 2, aba: 3, a: 4}**///obj是数组let obj = ['a','baaa','aba','a','aaaaa']obj = ksort(obj)/***结果*["aaaaa", "baaa", "aba", "a", "a"]**/