本文介绍了如何在JavaScript中为三元运算符返回true或false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用三元运算符将以下代码转换为速记版本

I'm trying to convert the code below to a shorthand version with a ternary operator

     if (sum % 10 === 0) {
        return true;
     } else {
        return false;
      }

它可以正常工作,但是当我将其更改为

It works fine as is, but when I change it to

sum % 10 === 0 ? return true : return false; 

我收到语法错误,并将其更改为

I get a syntax error, and when I change it to

sum % 10 === 0 ? true : false; 

它无法正常工作。

如果有人可以告诉我发生了什么事,我将不胜感激。

If anyone can enlighten me as to what's going on, I'd be much appreciated.

推荐答案

您尝试过的操作:

sum % 10 === 0 ? return true : return false; 

这不起作用,因为是一个语句,而不是表达式。

This does not work, because return is a statement and not an expression. A statement can not be used inside of an expression.

sum % 10 === 0 ? true : false; 

此方法有效,但没有 return 语句,它只是不使用它的一个表达式。

This works, but without a return statement, it is just an expression without using it.

最后,您需要还原,例如

Finally, you need to retur the result of the conditional (ternary) operator ?:, like

return sum % 10 === 0 ? true : false; 

对于较短的方法,您可以不加三元地返回比较结果。

For a shorter approach you could return the result of the comparison without ternary.

return sum % 10 === 0;

这篇关于如何在JavaScript中为三元运算符返回true或false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:45