我想知道为什么我的解决方案行不通。我有以下几点:
//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对象中为真时,则需要执行一些操作。因此,在我的示例中,如果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
}
});发布于 2016-09-29 18:30:38
你想做:
if ( item.type === "Plan" || isInReport[ item.type.toLowerCase() ] ) {
//do stuff
}有人评论说,这是不正确的。您能否确认您对report中的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");
}
});
发布于 2016-09-29 18:28:50
我没看到错误..。我在这里摆弄它:http://jsfiddle.net/Lnkky0fw/
$( document ).ready(function() {
var isInReport = {factual: true, eac: false, variance: false};
//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
var report = [{type: "Plan"},{type: "Factual"},{type: "EAC"},{type: "Variance"}];
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
alert('ok');
}
});
});发布于 2016-09-29 18:28:59
在“报表”数组中的元素之间缺少逗号。
https://stackoverflow.com/questions/39777386
复制相似问题