javascript - 为什么 JS 中带有多个语句的三元运算符不起作用?

标签 javascript reactjs conditional-operator

我知 Prop 有多个语句的三元运算符可以在 React/JavaScript 中使用:

条件? (语句1,语句2,...):(语句);

Explored了解它是如何工作的。

以下是我的代码,它导致了错误:

localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");

错误:

./src/reducers/reducer.js Line 26:21: Expected an assignment or function call and instead saw an expression no-unused-expressions

Search for the keywords to learn more about each error.

if/else 类似的代码工作正常:

if (localProducts[productFoundAt].qty > 0) {
    localProducts[productFoundAt].qty--;
    localCartedProducts[iterator].qty++
} else {
    alert("More quantity not available");
}

我在这里做错了什么?谢谢您的帮助。 另外为什么类似的代码在这里工作?

let a = 10;
let b = 10;

a==b ? (a-- , b--):alert("Hello World");
console.log(a);
console.log(b);

最佳答案

这是一个有效的语法。这只是一个 es-lint 错误,您可以通过添加以下行来忽略该错误:

/* eslint-disable no-unused-expressions */
localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");

希望这对您有用。

关于javascript - 为什么 JS 中带有多个语句的三元运算符不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968688/

相关文章:

javascript - OOP Javascript - "get property"方法是否必要?

javascript - 为什么遍历 ES6 Map 不会在 ReactJS 中创建任何子元素?

javascript - 从不同文件调用函数

c++ - 如何使 '<?=' 可用于 C++?

javascript - JQuery Animate 函数在制作动画之前跳转到屏幕顶部

javascript - 如何在数组中的每两个值之后将 js .join() 方法应用于我的数组

javascript - 删除按钮无法正常工作(DOM)

javascript - Ant Design - 在选择中搜索键和值

linux - BASH : find fileX[1-20] in directory Y and look if fileX[1-20]. pid 存在

c# - 检查整数然后返回字符串