用布尔值乘以安全(并且更好)?

时间:2015-11-04 20:11:33

标签: javascript boolean

我有一段代码,有很多if和else if。我现在只想到,在乘法中,true计算结果为1,false计算结果为0.是否安全且更容易阅读(因为它更短)替代:

if(!this._isFetched('studentInfoFetched')) { 
        tempAddedTime += 1;
        estimatedTimePerStudent += 0.04 + 0.2;
}
if(formInputValues.student_expiration){
        tempAddedTime += (!this._isFetched('studentExpirationFetched'))? 14 : 0;
        estimatedTimePerStudent += 1; 
}  

for:

    tempAddedTime += 1 * (!this._isFetched('studentInfoFetched')) + 14 * (!this._isFetched('studentExpirationFetched')) * (formInputValues.student_expiration);
    estimatedTimePerStudent += 0.24 * (!this._isFetched('studentInfoFetched')) + 1 * (formInputValues.student_expiration);

注意:_isFetched返回一个bool。这只是一个例子,对于其他情况我还有更多,如果这样可以节省更多行。

2 个答案:

答案 0 :(得分:9)

不,if s版本更好。

理由:

  • 它更具可读性:表达式更短,线条不会太长。例如,我在屏幕上看到了一个用于乘法表达式的水平滚动条,而我不必滚动if - 片段:)

  • 它更快,因为你避免了乘法。

  • 它更快,因为你避免两次调用this._isFetched('studentInfoFetched')

  • if在语义上定义了程序流,而乘法在语义上是一个数学表达式,在这种情况下用于伪造程序流。对于if s,语句按条件分组,您可以一眼看出如果满足某个条件会发生什么。

然后,考虑您必须再创建两个if子句。乘法将变得完全无法维持。

答案 1 :(得分:0)

代码应易于阅读,快速理解,并且快速更改。

比关闭时间的评论更好的是明确的变量名称,尽管它们对于为什么的一般描述是有益的。为常量命名常量(即什么是0.04 + 0.2 ??)和名称表达式(也避免了不必要的函数调用)。

// Estimate process time
const infoFetched = this._isFetched('studentInfoFetched')
const infoFetchTime = 0.04 + 0.2
const canExpire = formInputValues.student_expiration
const expirationFetched = this._isFetched('studentExpirationFetched')
const expirationFetchTime = 14

if (!infoFetched) tempAddedTime += 1
if (hasExpired && !expirationFetched) tempAddedTime += expirationFetchTime

if (!infoFetched) estimatedTimePerStudent += fetchTime
if (hasExpired) estimatedTimePerStudent += 1

我通常喜欢将布尔值作为切换倍增,尽管在这种情况下,if可能更容易阅读,理解和更改;

tempAddedTime +=
    !infoFetched* 1 +
    (hasExpired && !expirationFetched)* expirationFetchTime

estimatedTimePerStudent +=
    !infoFetched* fetchTime +
    hasExpired* 1

不是最好的例子,如果我能够访问/了解它所做的事情/来源,可能会有很大的不同

相关问题