我正在 html Canvas 上摆弄条件运算符,并且想要一种简单而有效的方法来使用条件运算符更改描边颜色。我似乎无法在网上找到一个可以在一行中完成此操作的好示例。
以下是我在没有条件运算符的情况下如何做到这一点:
if (shape.strokecolor == 'black'){
shape.strokecolor = 'red';
}
else if (shape.strokecolor == 'red'){
shape.strokecolor = 'black';
}
我认为我可以通过使用条件运算符来改进这一点。我发现这很有效:
var strokecol = shape.strokecolor == 'black' ?
shape.strokecolor = 'red' :
shape.strokecolor == 'red' ?
shape.strokecolor = 'black' :
shape.strokecolor = 'red';
所以这将是:
- 评估描边颜色是否为黑色
- 如果为 true,将其更改为红色,
- 如果为 false,则评估描边颜色是否为红色
- 如果为 true,将其更改为黑色,
- 如果为 false,请将其保留为红色。
最后一行似乎是运算符结构所必需的,但对我来说是多余的。我似乎还必须将结果分配给一个变量,但我不需要这样做,因为更改无论如何都会生效。我认为使用条件运算符会减少我的代码,但这种方式并没有真正的帮助。
我觉得我做得不对... 我的主要问题是,我是否可以使用这样的条件运算符而不分配给变量,其次,是否有人知道如何尽可能有效地改进给定的代码(使用或不使用条件运算符)?谢谢。
最佳答案
使用条件运算符来生成值,而不是副作用(如赋值)。然后您可以将该值分配给适当的位置。如果唯一可能的颜色是黑色和红色,你会这样写:
shape.strokecolor = shape.strokecolor == 'black' ? 'red' : 'black';
要保持其他颜色的原始行为,您需要将该属性分配回其自身:
shape.strokecolor = shape.strokecolor == 'black' ? 'red' :
shape.strokecolor == 'red' ? 'black' :
shape.strokecolor;
但这并不比原来的 if
更好。
关于javascript - 不分配给变量的条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48116646/