gpt4 book ai didi

javascript - 测试多个三元运算符 Javascript 的 If 语句

转载 作者:行者123 更新时间:2023-12-03 06:00:15 25 4
gpt4 key购买 nike

我想知道为什么我的解决方案不起作用。我有以下内容:

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];

我需要循环遍历报告数组,如果 item.type 是“Plan”,或者它是其他 3 种类型之一,但前提是它在 isInReport 对象中为 true,则始终执行某些操作。因此,在我的示例中,如果 item.type 是“计划”或“事实”,则 if 语句应该通过

为什么这段代码不起作用?这个逻辑对我来说似乎是正确的,尽管有点奇怪。当我测试时,无论如何它总是返回所有类型。感谢您的帮助!

report.map(function (item) {
if (
item.type === "Plan" ||
item.type === (isInReport.factual) ? "Factual" : "Plan" ||
item.type === (isInReport.eac) ? "EAC" : "Plan" ||
item.type === (isInReport.variance) ? "Variance" : "Plan"
) {
//do stuff
}
});

最佳答案

你想做什么:

if ( item.type === "Plan" || isInReport[ item.type.toLowerCase() ] ) {
//do stuff
}

有评论表明这是不正确的。您能否确认报告中的 4 项结果是否符合您的预期?

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];

report.forEach(function(item){
if ( item.type === "Plan" || isInReport[ item.type.toLowerCase() ] ) {
console.log("Item Type:" + item.type + " PASSED TEST");
} else {
console.log("Item Type:" + item.type + " FAILED TEST");
}
});

如果您想坚持一开始的方式,那么您需要使用一些括号来更好地控制顺序或操作。

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];

report.forEach(function(item){
if (
item.type === "Plan" ||
item.type === (isInReport.factual ? "Factual" : "Plan") ||
item.type === (isInReport.eac ? "EAC" : "Plan") ||
item.type === (isInReport.variance ? "Variance" : "Plan")
) {
console.log("Item Type:" + item.type + " PASSED TEST");
} else {
console.log("Item Type:" + item.type + " FAILED TEST");
}
});

关于javascript - 测试多个三元运算符 Javascript 的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com