把下面的数据
{
"name_a":{"price":100},
"name_b":{"price":400},
"name_c":{"price":200},
"name_d":{"price":300}
}
按照价格升序排列,例如:
<p>名称:name_a价格100 </p>
<p>名称:name_c价格200</p>
<p>名称:name_d价格300</p>
<p>名称:name_b价格400</p>
注意是带着HTML符号。
参考答案:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="div">
</div>
<script>
var div = document.getElementById("div");
var data = {
"name_a": {"price": 100},
"name_b": {"price": 400},
"name_c": {"price": 200},
"name_d": {"price": 300}
}
var prices = [];
for (var name in data) {
// console.log(data[name]);
prices.push(data[name].price);
}
function randomSort() {
return Math.random() - 0.5;
}
prices.sort();
// prices.sort(randomSort);
var output = [];
var length = prices.length;
for (var i = 0; i < length; ++i) {
for (var name in data) {
if (data[name].price == prices[i]) {
// console.log(name);
output.push("<p>名称:" + name + "价格" + prices[i] + "</p>");
break;
}
}
}
// console.log(output.join(""));
div.innerHTML = output.join("");
</script>
</body>
</html>
其中:用数组的元素组成字符串 - join()