首页 > 解决方案 > forEach 方法没有在 TypeScript 中正确设置布尔类型

问题描述

我有一个简单的函数,在里面我试图为 false 或 true 设置一些布尔值。布尔值始终为 false,但在 forEach 方法中它应该设置为 true - 问题似乎更奇怪,因为在 forEach 方法中有一个“if 语句”,它检查布尔值是否应该设置为 true 或假设留作假。看代码应该更全面——问题本身似乎微不足道。

实际上这里没什么可做的——我尝试了一些代码调整,但都没有奏效。

exists: boolean; //here's the variable declaration at the beginning of the class

onCreateFolder(nodeId) { //the actual function

this.exists = false;

this.nodeService.getNodeChildren(nodeId).forEach(
  node => {
    node.list.entries.forEach(
      actualNode => {
        if(actualNode.entry.isFolder && actualNode.entry.name === theName) {
          this.exists = true;
          this.existingFolderId = actualNode.entry.id;
          console.log("Found the existing folder! " + this.existingFolderId); //console log is beeing printed - so the if statement is true at least once so as this.exists should be set to true
        }
      }
    )
  }
)

//after leaving the method above the it seems like this.exists goes back to false(?)

  if(!this.exists) {

  //always get into

  } else if(this.exists) {

  //never get into

  }


}

上面 forEach 方法中的 if 语句为真 - 关于查找实际文件夹的控制台日志正在打印,因此“this.exists” - 应该设置为真,但当它离开时 - 有后者的 if 和 else if 语句,看起来像“this.exists”总是错误的。

标签: typescript

解决方案


推荐阅读