21,886
社区成员
发帖
与我相关
我的任务
分享
var menuArr = new Array();
//索引,名称,父节点号
menuArr[1] = ["中国", 0];
menuArr[2] = ["美国", 0];
menuArr[3] = ["日本", 0];
menuArr[4] = ["浙江", 1];
menuArr[5] = ["福建", 1];
menuArr[6] = ["东京", 3];
menuArr[7] = ["杭州", 4];
menuArr[8] = ["温州", 4];
menuArr[9] = ["鹿城", 8];
//menuArr[i][0] //menuArr[i][0]
//求给定一个数组index号,如,遍历menuArr ,要求判断:1 ,该节点在树中等级,第几级;2判断该节点是否排在同一级的末尾---即本节点后面是否还有兄弟节点?3,求该节点的路径:即从根节点到该节点的所有父级的索引号:即父级的父级直至根节点的索号!
var menuArr = new Array();
//索引,名称,父节点号
menuArr[1] = ["中国", 0];
menuArr[2] = ["美国", 0];
menuArr[3] = ["日本", 0];
menuArr[4] = ["浙江", 1];
menuArr[5] = ["福建", 1];
menuArr[6] = ["东京", 3];
menuArr[7] = ["杭州", 4];
menuArr[8] = ["温州", 4];
menuArr[9] = ["鹿城", 8];
menuArr[10] = ["广西", 1];
//=============================================
function lookThrough(Arr){
this.Arr=Arr;
this.splitArrayByPId();//分类节点
}
lookThrough.prototype.reset=function(str){
this.level=str?str:1;//第几级
this.endNode=str?str:false;//是否同级的末尾
this.path=str?str:new Array();//清空路径或者设置错误信息,注意此时存储的路径是当前节点到父节点,所以最后需要反转
this.wordPath=str?str:new Array();
}
lookThrough.prototype.toString=function(){
return "该节点在树中等级:"+this.level
+"\n\n该节点是否在末尾:"+this.endNode
+"\n\n路径:"+(typeof(this.path.join)!="undefined"?this.path.join("=>"):this.path)
+"\n\n文字路径:"+(typeof(this.wordPath.join)!="undefined"?this.wordPath.join("=>"):this.wordPath);
}
lookThrough.prototype.getWordPath=function(){
if(typeof(this.path)=="string")return;
var item;
for(var i=0;i<this.path.length;i++){
item=this.Arr[this.path[i]]
this.wordPath.push(item?item[0]:"根");
}
}
lookThrough.prototype.splitArrayByPId=function(){
this.Level=[];
var item;
for(var i=0;i<this.Arr.length;i++){
item=this.Arr[i];
if(!item)continue;//过滤数组中未使用的索引
if(!this.Level[item[1]])this.Level[item[1]]=new Array();
this.Level[item[1]].push({mIndex:i});
}
}
lookThrough.prototype.getLevelAndPath=function(Index){
var pId=this.Arr[Index][1];
this.path.push(pId);
while(this.Arr[pId]){
pId=this.Arr[pId][1]
this.path.push(pId)
this.level++;
}
}
lookThrough.prototype.go=function(Index){
if(!this.Arr[Index]){
this.reset('给的索引号不正确或者未在数组中!');return;
}
this.reset();
this.path.push(Index);//推入当前节点
this.getLevelAndPath(Index);
this.path.reverse();//============反转
this.getWordPath();
var SameLevel=this.Level[this.Arr[Index][1]];//获取拥有同一个父节点号的数组
if(SameLevel[SameLevel.length-1].mIndex==Index)this.endNode=true;
else this.endNode=false;
}
//======================Test===========================
var o=new lookThrough(menuArr);
o.go(1)
alert(o.toString())
o.go(10)
alert(o.toString())
o.go(4)
alert(o.toString())
o.go(7)
alert(o.toString())
o.go(8)
alert(o.toString())
o.go(20)
alert(o.toString())