猿问

js对象中按照字母多少例如var obj={'a','baaa','aba','a','aaaaa'

var obj={'a','baaa','aba','a','aaaaa'}
怎样按照a的数量从大排到小

米琪卡哇伊
浏览 489回答 3
3回答

幕布斯6054654

obj应该是个数组吧var obj =['a','baaa','aba','a','aaaaa']obj.sort(function(a, b) { return a.length > b.length}) // 从小到大obj.sort(function(a, b) { return a.length < b.length}) // 从大到小

qq_笑_17

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

有只小跳蛙

首先,你的对象定义都是错误的吧?是否应该是数组?其次对象中key是无序的(程序实现中不保证对象属性存储有序,你只能先提取key,为数组,再对这个数组排序,然后依据数组输出元素信息来保证有序输出。)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答