为什么不能使用条件运算符来像这样有条件地增加属性? [英] Why can’t conditional operator be used to conditionally increment property like this?
本文介绍了为什么不能使用条件运算符来像这样有条件地增加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我在使用条件运算符时会收到 linter 警告,而使用简单的 if
语句却没有?
Why do I receive a linter warning when using the conditional operator, but using a simple if
statement does not?
switch (type) {
case 'add':
array[index]['Quantity'] += 1;
// Error when using `++array[index]['Quantity']`
break;
case 'remove':
array[index]['Quantity'] > 0 ? array[index]['Quantity'] -= 1 : null;
// Error: Expected an assignment or function call and instead saw an expression (no-unused-expressions)
break;
default:
break;
}
可能的方式
switch (type) {
case 'add':
array[index]['Quantity'] += 1;
break;
case 'remove':
if (array[index]['Quantity'] > 0) {
--array[index]['Quantity'];
}
break;
default:
break;
}
推荐答案
我认为这是问题所在:
array[index]['Quantity'] > 0 ? array[index]['Quantity']-=1 : 0; // Error
break;
当三元条件为真时,您将返回一个表达式 (array[index]['Quantity']-=1),而您应该返回一个值.
You are returning an expression (array[index]['Quantity']-=1) when the ternary condition is true, when you should be returning a value.
试试这个:
array[index]['Quantity'] = array[index]['Quantity'] > 0 ? array[index]['Quantity'] - 1 : 0;
break;
但我仍然认为这是最好的解决方案:
But I still think this is the best solution:
if (array[index]['Quantity'] > 0)
array[index]['Quantity']--;
break;
这篇关于为什么不能使用条件运算符来像这样有条件地增加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文