在javascript中防止/处理除以0的最佳方法 [英] Best way to prevent/handle divide by 0 in javascript
本文介绍了在javascript中防止/处理除以0的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在接受用户输入的javascript中,防止除以0的最佳方法是什么?
如果没有特定的方法来实现这一点,那么处理这种情况的最佳方法是什么,以免阻止其他脚本执行?
What is the best way to prevent divide by 0 in javascript that is accepting user inputs. If there is no particular way to achieve this what would be the best way to handle such a situation so as to not prevent other scripts from executing?
任何非常感谢。
推荐答案
正常 / $无法做到这一点c $ c>和
/ =
运营商。
做你想做的事情的最好办法就是守卫: / p>
The best way to do what you want is with guards:
function notZero(n) {
n = +n; // Coerce to number.
if (!n) { // Matches +0, -0, NaN
throw new Error('Invalid dividend ' + n);
}
return n;
}
然后像
numerator / notZero(denominator)
或者你可以随时保护输出
Alternatively you can always guard the output
function dividend(numerator, denominator) {
var quotient = numerator / denominator;
if (quotient !== quotient) { throw new Error(numerator + " / " + denominator); }
return quotient;
}
但是会失去 / =的可读性和表现力
。
这篇关于在javascript中防止/处理除以0的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文