我想知道为什么我的解决方案无法正常工作。我有以下几点:如果测试多个三元运算符的语句Javascript
//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"}];
我需要遍历数组报告,并做一些事情总是如果项目。形式是“规划纲要”,或者如果是其他3种类型之一,但只有当它是在isInReport对象中为true。所以在我的例子中,如果item.type是“Plan”或“Factual”,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
}
});
也许你需要'report.filter '而不是另外? – apokryfos
如果行'report = [{type:“Plan”} {type:“Factual”} {type:“EAC”} {type:“Variance”}];'是正确的,你能重新检查一下吗?似乎缺少了许多逗号,例如:'report = [{type:“Plan”},{type:“Factual”},{type:“EAC”},{type:“Variance”}];'另外,你是否可以确认'item.type ===“Plan”'是否正确,[不需要更多的检查,因为语句已经是真实的](https://developer.mozilla.org/en/docs/Glossary/Truthy) – Bonatti
不知道你的问题在哪里,无论如何,即使这个代码工作,如果你可以改变它,它应该是一个很好的可读性更好的形式。 * if *条件中不需要三元运算符! –