javascript - 如何检查布尔值是否作为字符串传递?
问题描述
所以在下面的代码中,如果我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
}]);
解决方案
您的示例代码使用字符串值“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: ""
}
]);
推荐阅读
- android - Firebase实时数据库可以在调用监听器时删除监听器吗
- python - 具有不同数据类型的 Numpy
- swift - Swift 4 支持 swagger 代码生成
- html - 使用 Angular 获取网站 URL 的 html
- python - Tensorflow:为什么必须在声明变量后声明`saver = tf.train.Saver()`?
- java - 动态属性的定制框架值得去吗?
- javascript - 覆盖对象引用的值
- java - 外键作为主键注解
- java - 错误:无法在 Textpad 8 中找到或加载主类
- asp.net-mvc - Solr 和 Aws CloudSearch 中的 API 有何区别?