//这样声明一个方法居然报错
// createPrefix(n:number):string {
// return '--'.repeat(n)
// }
function createPrefix(n:number):string {
return '--'.repeat(n)
}
// class XXX {
// public children = []
// constructor (public name : string){}
// addChild(){
// console.log('object');
// }
// introduceFamily(){
// console.log('22');
// }
// }
{
class Person {
//Person[] 传入的参数,必须是new Person这个对象的,或者有它的所有方法如上class XXX....
public children:Person[] = [] //默认值[]
// constructor(public name: string) {}
//加public相当于简写
//name :string
//constructor(name){
// this.name = name
// }
constructor(public name: string) {}
addChild(child:Person):void {
this.children.push(child);
}
introduceFamily(n?:number):void{
n = n || 1
console.log(`${createPrefix(n-1)}${this.name}`);
this.children.forEach(child =>{
//有子代就加1
child.introduceFamily(n+1)
})
}
}
let grandPa = new Person('孙悟饭');
let child1 = new Person('孙悟天');
let child2 = new Person('孙悟空');
let person1 = new Person('孙悟静');
let person2 = new Person('孙悟');
let person3 = new Person('孙悟芳');
grandPa.addChild(child1)
grandPa.addChild(child2)
child2.addChild(person1)
child2.addChild(person2)
child2.addChild(person3)
grandPa.introduceFamily(1)
//可运用与类似循环遍历家谱、找文件夹等等,这样一级一级的结构
}
TypeScript-class学习笔记---遍历Tree
猜你喜欢
转载自blog.csdn.net/qq_42220283/article/details/104422589
今日推荐
周排行