美文网首页
用ts打印族谱

用ts打印族谱

作者: 郑无穷大 | 来源:发表于2018-10-22 13:44 被阅读0次

    以下是代码

    #!/usr/bin/env ts-node
    function createPrefix(n: number):string {
        return '----'.repeat(n);
    }
    {
        class Person {
            public children: Person[] = []; //前面是类型声明,后面必须要初始赋值,不然就是undefined
            constructor(public name: string) {}
            addChild(child: Person): void { //什么也不返回就添加void
                this.children.push(child);
            }
            introduceFamily(n?: number): void { // ?表示可选参数
                n = n || 1
                console.log(`${createPrefix(n-1)}${this.name}`)
                this.children.forEach((child)=>{
                    child.introduceFamily(n+1);
                });
            }
        }
    
        let grandPa = new Person('王大');
        let child1 = new Person('王小');
        let child2 = new Person('王小二');
        let person1 = new Person('王小小');
        let person2 = new Person('王二二');
    
        grandPa.addChild(child1);
        grandPa.addChild(child2);
    
        child1.addChild(person1);
        child2.addChild(person2);
    
        grandPa.introduceFamily();
    }
    

    相关文章

      网友评论

          本文标题:用ts打印族谱

          本文链接:https://www.haomeiwen.com/subject/vmxgzftx.html