首页 > 解决方案 > 如何在三元语句中使用 OR 运算符

问题描述

我正在尝试使用 OR 和使用三元运算符的 if else 条件来测试代码。我可以使用正常的 if else 获得正确的结果,但是当我切换到使用三元运算符时..我没有得到相同的结果。有谁知道为什么 OR 不适用于三元运算符?

我尝试对 if/else 和三元运算符使用相同的 OR 代码...三元不返回我期望的结果

var prodIdCond = excludedOffers.indexOf(prod_id) == -1;

//作品

if (String(offer.getValue('availability')) == 'in stock' || prodIdCond) { 
    console.log('active')
} else {
    console.log('paused')
}

//不起作用

(inStockCond || prodIdCond) ? console.log('active') : 
console.log('paused');

我希望在未找到 prod_id 时输出为“活动”.. 但是当我使用三元运算符时,即使找到了 prod_id.. 它也会返回“活动”

标签: javascript

解决方案


You intentions are not really clear here but,

I expect output to be 'active' when prod_id is not found.. but when I use ternary operators, even if the prod_id is found.. it returns 'active'

Your initial if statement does not accomplish this. It will return active regardless of whether the prod_id is found or not, if the inStockCond is met.

To ensure that active is not returned when prod_id is found, you have to use the logical && operator, (which has other implications on your predicate which you will have to fix accordingly). This guarantees that active is only returned when the prod_id is not found. But also only when inStockCond is met.

(inStockCond && prodIdCond) ? console.log('active') : console.log('paused');

Note that a unit of execution in most languages is either a statement or an expression. Expressions are meant to be used to evaluate something and return a value while statements are meant to execute instructions with no regards to return values.

The "correct" way to express this would be

console.log(inStockCond && prodIdCond ? 'active' : 'paused');

where the ternary expression inside log is evaluated first and the return value passed to the console.log() statement.

But the magic of javascript is that even methods with no return values return a special value called undefined allowing you to nest console.log statements inside expressions. The line between expressions and statements are effectively blurred.


推荐阅读