实现思路: 将带空格分隔的字符串split成数组,利用数组sort()排序方法,在该方法里面用chartCodeAt()方法比对元素间同位置的字符的ASCII码(同一位置字符的ASCII码相同则继续比对下一个字符)
var dic = {
2: {"score": 20},
1: {"score": 25},
3: {"score": 15},
4: {"score": 60},
}
console.log("输出最初的字典元素: ")
for(var key in dic){
console.log("key: " + key + " ,value: " + dic[key])
}
console.log("字典元素按key值排序: ")
var res = Object.keys(dic).sort()
for(var key in res){
console.log("key: " + res[key] + " ,value: " + dic[res[key]])
}
console.log("字典元素按value值排序: ")
var res2 = Object.keys(dic).sort(function(a,b){ return dic[a]["score"]-dic[b]["score"] })
for(var key in res2){
console.log("key: " + res2[key] + " ,value: " + dic[res2[key]])
}
原文链接:https://blog.csdn.net/juyuyh/article/details/89948380