javascript - 如何在三元语句中使用 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.. 它也会返回“活动”
解决方案
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.
推荐阅读
- c# - C# BLE DeviceConnectionChanged 事件多次触发,直到关闭设备
- python-3.x - Tesseract-OCR 无法在某些图像中找到文本
- r - 使用插入符号的岭逻辑回归系数的标准误差
- apache-poi - 使用 POI 限制编辑 Word 文件中的特定部分
- java - 解压后日期以毫秒的形式出现 - 不同机器上的不同行为
- json - 有没有办法从 Go 中的给定 JSON 中提取 JSON Schema?
- java - 如何将 JTextArea 对象放置在 JPanel 上的某个位置?
- python - 使用此 Python 脚本将立方体贴图转换为 equirectangular
- function - Lua - 连接传递给函数的几个参数,直到满足条件,然后将字符串传递给下一个函数
- css - 如何在 Angular 8 中覆盖自定义组件 css