js 字典排序


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]]);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM