这些JS条件语句在功能上是否相同? [英] Are these JS conditional statements functionally equivalent?

查看:116
本文介绍了这些JS条件语句在功能上是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于条件if / else语句,以下示例在功能上是等效的吗?

Regarding conditional if/else statements, are the following examples functionally equivalent?

function isEntering() {
    if (this.stage === 'entering') {
        return true;
    } else {
        return false;
    }
}

function isEntering() {
    if (this.stage === 'entering') {
        return true;
    } return false;
}

function isEntering() {
    if (this.stage === 'entering') {
        return true;
    } 
}

isEntering = (this.stage === 'entering') ? true : false;

如果是这样,我会使用最简洁的选项。但是,只有这四个在功能上是等价的。

If so, I'd use the most terse of the options. But only if the four are functionally equivalent.

推荐答案

如果 expr 是一个布尔表达式,就像在这里一样,那么就没有必要写

If expr is a boolean expression, as it is here, then there is no need to write

if (expr) return true;
else return false;

或写

if (expr) x = true;
else x = false;

或永远写

expr ? true : false

因为是一个布尔表达式, expr 可以直接退回或分配:

because being a boolean expression, expr can be returned, or assigned, directly:

return expr;

x = expr;

最简洁的选择是你没有给出的选择:

The tersest alternative is one you didn't give:

function isEntering() { return this.stage === 'entering'; }

这篇关于这些JS条件语句在功能上是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆