我想知道爲什麼我的解決方案無法正常工作。我有以下幾點:如果測試多個三元運算符的語句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 *條件中不需要三元運算符! –