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
<!DOCTYPE HTML><html>
<head>
<meta charset="UTF-8" />
<title>main.html</title>
<style type="text/css">
table {
width: 300pxborder : 1px solid black
border-collapse: collapse
border: 1px solid black
}
td {
border: 1px solid black
}
</style>
<script type="text/javascript">
function paiXu ()
{
var tabNode = document.getElementsByTagName ("table")[0]
var trs = tabNode.rows
var arr = new Array
for ( var x = 0x <trs.lengthx++)
{
arr.push (trs[x])
}
sortt (arr)
for ( var x = 0x <arr.lengthx++)
{
tabNode.tBodies[0].appendChild (arr[x])
}
}
function sortt (arr)
{
for ( var x = 0x <arr.lengthx++)
{
for ( var y = x + 1y <arr.lengthy++)
{
if (parseInt (arr[x].cells[1].childNodes[0].nodeValue) <= parseInt (arr[y].cells[1].childNodes[0].nodeValue))
{
var tmp = arr[x]
arr[x] = arr[y]
arr[y] = tmp
}
}
}
}
</script>
</head>
<body>
<input type="button" value="排序" onclick="paiXu()">
<table>
<tr>
<td>小明</td>
<td>23</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>小花</td>
<td>21</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>小高</td>
<td>12</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>小林</td>
<td>25</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>小王</td>
<td>35</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>