代码之家  ›  专栏  ›  技术社区  ›  minizibi

类型脚本递归检查条件

  •  -1
  • minizibi  · 技术社区  · 7 年前

    您好,我有一个对象结构,它完全像这样:

    Category {
     id: number;
     nestedCategories: Category[];
    }
    

    现在我需要使用递归来检查在父类或任何子类中是否存在给定ID的类别,方法签名看起来是这样的:

    checkIfExists(cat: Category) {
        return this.categoryViewService
          .getRawCategories()
          .filter(notChildren(cat));
    }
    
    notChildren(cat: Category) {
        //?
    }
    

    由于Javascript语言的作用域,我这里有问题,有人能帮我吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   AleÅ¡ Dostál    7 年前

    方法筛选器将参数作为方法回调。可能是,您可以尝试:

    发件人:

    checkIfExists(cat: Category) {
        return this.categoryViewService
          .getRawCategories()
          .filter(notChildren(cat));
    }
    
    notChildren(cat: Category) {
        //?
    }
    

    致:

    checkIfExists(cat: Category) {
        return this.categoryViewService
          .getRawCategories()
          .filter(notChildren);
    }
    
    notChildren(cat: Category) {
        //?
    }