首页 > 解决方案 > 如何检查布尔值是否作为字符串传递?

问题描述

所以在下面的代码中,如果我ancillaryProductInd作为布尔代码传递,但是当我将它作为字符串传递时,它不起作用。据我了解,以下代码仅在我传递“false”字符串值并在布尔值上抛出错误时才有效。知道这里有什么问题吗?

main.ts

要求

var rxInfos = [{
  "ancillaryProductInd": "false",
  "indexID": "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}]


function subQuestionsHandler(rxInfos, data) {
  const subQuestionArray = [];
  rxInfos.forEach((rxInfo) => {
    const subQuestion = {
      question: []
    };
    if (rxInfo.ancillaryProductInd !== undefined && rxInfo.ancillaryProductInd === "false") {
      subQuestion.question = data;
      subQuestionArray.push(subQuestion);
    }
  });
  return subQuestionArray;
}

subQuestionsHandler(rxInfos, [{
  some data
}]);

标签: javascriptarraysif-statement

解决方案


您的示例代码使用字符串值“false”按预期工作,并且在使用布尔值时不运行 if 块。看我的例子:

var rxInfos = [
  {
    ancillaryProductInd: "false",
    indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
  },
  {
    ancillaryProductInd: false,
    indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
  }
];

function subQuestionsHandler(rxInfos, data) {
  const subQuestionArray = [];
  rxInfos.forEach(rxInfo => {
    const subQuestion = {
      question: []
    };
    if (
      rxInfo.ancillaryProductInd !== undefined &&
      rxInfo.ancillaryProductInd === "false"
    ) {
      console.log("no error");
      subQuestion.question = data;
      subQuestionArray.push(subQuestion);
    } else {
      console.log("throw error");
    }
  });
  return subQuestionArray;
}

subQuestionsHandler(rxInfos, [
  {
    test: ""
  }
]);

推荐阅读