性能优化的话,应该主要是减少for的次数。
思路:先整体for一遍,能创建的先创建,碰到父级项目还没创建的子项目,先用个数组cache起来,等for结束,所有的父级项目都创建完成了,然后把cache的项目加进去,这样应该可以减少一些循环次数。
情况一:如果JSON能够按照项目的层级排序,把父级项目都放在前面的话,只要一次for就可以全部搞定。
情况二:如果大多数父级项目都排在后面的话,可能反而增加了for的次数,不过应该比楼主的方法还是要节省一些,最多只有两次for。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var data = [
{ "cid": "1", "name": "品牌1", "pid": "0" },
{ "cid": "2", "name": "品牌2", "pid": "0" },
{ "cid": "3", "name": "品牌3", "pid": "1" },
{ "cid": "4", "name": "品牌4", "pid": "2" },
{ "cid": "5", "name": "品牌5", "pid": "1" }
];
window.onload = function() {
for (var i = 0; i < data.length; i++) {
if (data[i].pid == 0) {
var ul = document.createElement("ul");
var li = document.createElement('li');
li.innerHTML = data[i].name;
ul.appendChild(li);
for (var k = 0; k < data.length; k++) {
if (data[k].pid == data[i].cid) {
var ul1 = document.createElement("ul");
var li1 = document.createElement('li');
li1.innerHTML = data[k].name;
ul1.appendChild(li1);
li.appendChild(ul1);
}
}
document.body.appendChild(ul);
}
}
}
</script>
</head>
<body>
</body>
</html>
方法二
<script>
function showJSON() {
var user =
{
"cate" : [{"cid" : "1","name" : "品牌1","pid" : "0"},
{"cid" : "2","name" : "品牌2","pid" : "0"},
{"cid" : "3","name" : "品牌3","pid" : "1"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "0"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "4"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "4"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "4"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "4","name" : "品牌4","pid" : "2"},
{"cid" : "5","name" : "品牌5","pid" : "1"}
]
}
var l = user.cate.length;
for(var i=0;i < l;i++){
if(user.cate[i].pid == "0"){
document.write(user.cate[i].name + "<br>");
for(var j=0; j < l ;j++){
if(user.cate[j].pid == user.cate[i].cid){
document.write(" ");
document.write(user.cate[j].name + "<br>");
}
}
}
}
}
showJSON()
</script>