Javascript 在javascript中防止/处理除以0的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8072323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to prevent/handle divide by 0 in javascript
提问by dibs
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?
在接受用户输入的javascript中防止被0除的最佳方法是什么。如果没有特定的方法来实现这一点,那么处理这种情况以便不阻止其他脚本执行的最佳方法是什么?
Any insights are much appreciated.
任何见解都非常感谢。
采纳答案by Mike Samuel
There is no way to do that with the normal /
and /=
operators.
普通/
和/=
运算符无法做到这一点。
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;
}
and then do division like
然后做除法
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;
}
but that loses the readability and expressiveness of /=
.
但这失去了 的可读性和表现力/=
。
回答by maerics
Off the top of my head you could:
在我的脑海里,你可以:
- Check the user input to see if the denominator is zero (or evaluates to zero, depending on what your script actually does).
- Check if the result of the action
isFinite()
and if not then handle appropriately.
- 检查用户输入以查看分母是否为零(或计算结果为零,具体取决于您的脚本实际执行的操作)。
- 检查操作的结果,
isFinite()
如果不是,则进行适当的处理。
回答by am2124429
what would be the best way to handle such a situation so as to not prevent other scripts from executing
处理这种情况的最佳方法是什么,以免阻止其他脚本执行
Division by zero doesn't seem to prevent other scripts from execution in JavaScript:
除以零似乎不会阻止其他脚本在 JavaScript 中执行:
var a = 20;
var b = 0;
var result = a/b;
console.log(result); // returns Infinity
If you want something different to happen in case of division by zero, you could use
如果您希望在除以零的情况下发生不同的事情,您可以使用
function divideIfNotZero(numerator, denominator) {
if (denominator === 0 || isNaN(denominator)) {
return null;
}
else {
return numerator / denominator;
}
}
回答by AlexMethod
Hope this is useful
希望这是有用的
(denominator != 0 ? numerator/denominator : Infinity)
or whatever value you want to put at the end.
或者你想放在最后的任何值。
Greetings.
你好。
回答by Smamatti
To prevent (unwanted) execution
防止(不需要的)执行
- Always verify criticaluser input and/or results
- Use logic and/or callbacks you can prevent to execute
- On HTML forms etc. you can use i.e.
return false;
as value to stop submission.
- 始终验证关键的用户输入和/或结果
- 使用可以阻止执行的逻辑和/或回调
- 在 HTML 表单等上,您可以使用 ie
return false;
作为停止提交的值。
回答by GAgnew
Why not just check if the denominator is zero?
为什么不检查分母是否为零?
if(x != 0) z = y / x;
You can also check if the result is Infinity:
您还可以检查结果是否为 Infinity:
3 / 0 == Infinity
Results in true
;
结果在true
;
(Only tested in chrome.)
(仅在 chrome 中测试。)
回答by Beejor
The best way is contextual. But here's the easiest:
最好的方法是上下文。但这是最简单的:
function myFunction( input ){
input = 0 ? 0.0001 : input; // same as if( input == 0 ){ input = 0.0001; }
return 1 / input;
}
Basically if the input is zero, turn it into a very small number before using as a denominator. Works great for integers, since after your division you can round them back down.
基本上,如果输入为零,则在用作分母之前将其变成一个非常小的数字。非常适合整数,因为在你除法之后你可以把它们四舍五入。
A couple caveats prevent this from being universal:
有几个警告阻止了它的普遍性:
- It could cause false positives if your input accepts really small numbers
- It won't trigger any error-handling code, if you need to do something special if zero is entered
- 如果您的输入接受非常小的数字,则可能会导致误报
- 它不会触发任何错误处理代码,如果您需要在输入零时做一些特殊的事情
So it's best for general-purpose, non-critical cases. For example, if you need to return the result of a complex calculation and don't care if the answer is accurate to N digits (determined by 0.0001 vs. 0.00000001, etc.); you just don't want it to break on a divide-by-zero.
所以它最适合通用的、非关键的情况。例如,如果您需要返回一个复杂计算的结果,并且不关心答案是否准确到 N 位(由 0.0001 与 0.00000001 等确定);你只是不希望它在被零除时中断。
As another answer suggested, you could also create a reusable global function.
正如另一个答案所建议的那样,您还可以创建一个可重用的全局函数。
function divisor( n ){ return ( n = 0 ? 0.0001 : n ); }
function myFunction( input ){ return 1 / divisor( input ); }
Possible improvements:
可能的改进:
function divisor( n, orError ){
if( typeof n == 'undefined' || isNaN( n ) || !n ){
if( orError ){ throw new Error( 'Divide by zero.' ); }
return 0.000000000000001;
}else{ return 0 + n; }
}
This would take anyvalue (null, number, string, object) and if invalid or zero, return the failsafe zero-like value. It would also coerce the output to a number just in case it was a string and you were doing something odd. All this would ensure that your divisor function always worked. Finally, for cases where you wanted to handle such errors yourself, you could set the second parameter to true and use a try/catch
.
这将采用任何值(空值、数字、字符串、对象),如果无效或为零,则返回类似故障安全的零值。它还会将输出强制为一个数字,以防万一它是一个字符串并且您正在做一些奇怪的事情。所有这些都将确保您的除数函数始终有效。最后,对于您想自己处理此类错误的情况,您可以将第二个参数设置为 true 并使用try/catch
.
回答by ShaneSauce
A bit different than stopping execution, but the ternary operator is a pretty slick way to customize variable assignment.
与停止执行有点不同,但三元运算符是自定义变量赋值的一种非常巧妙的方法。
var one = 1,
zero = 0,
customValue = 1;
var quotient = zero===0 ? customValue : one / zero;
This way, by setting the customVariable to the integer of your choice, you can expect a predictable result when division by zero occurs.
这样,通过将 customVariable 设置为您选择的整数,您可以在除以零时获得可预测的结果。