Ant*_* N. 5 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;
}
Run Code Online (Sandbox Code Playgroud)
用于:
tempAddedTime += 1 * (!this._isFetched('studentInfoFetched')) + 14 * (!this._isFetched('studentExpirationFetched')) * (formInputValues.student_expiration);
estimatedTimePerStudent += 0.24 * (!this._isFetched('studentInfoFetched')) + 1 * (formInputValues.student_expiration);
Run Code Online (Sandbox Code Playgroud)
注意:_isFetched返回一个bool.这只是一个例子,对于其他情况我还有更多,如果这样可以节省更多的线.
不,ifs版本更好.
原因:
它更具可读性:表达式更短,线条不会太长.例如,我在屏幕上看到一个水平滚动条用于乘法表达式,而我不必在if-snippet中滚动:)
它更快,因为你避免了乘法.
它甚至更快,因为你避免this._isFetched('studentInfoFetched')两次打电话.
ifs语义定义程序流,而乘法在语义上是一个数学表达式,在这种情况下用于伪造程序流.使用ifs,语句按条件分组,您可以一目了然地看到如果满足某个条件会发生什么.
然后,考虑您必须再创建两个if子句.乘法将变得完全无法维持.