在接受用户输入的javascript中,防止除以0的最佳方法是什么? 如果没有特定的方法来实现这一点,那么处理这种情况的最佳方法是什么,以免阻止其他脚本执行?
非常感谢任何见解。
答案 0 :(得分:18)
使用普通/
和/=
运算符无法做到这一点。
做你想做的事的最好办法就是守卫:
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)
或者你可以随时保护输出
function dividend(numerator, denominator) {
var quotient = numerator / denominator;
if (quotient !== quotient) { throw new Error(numerator + " / " + denominator); }
return quotient;
}
但是这会失去/=
的可读性和表现力。
答案 1 :(得分:5)
离开我的头顶你可以:
isFinite()
的结果是否正确处理。答案 2 :(得分:4)
处理这种情况的最佳方法是什么,以免阻止其他脚本执行
除以零似乎不会阻止其他脚本在JavaScript中执行:
var a = 20;
var b = 0;
var result = a/b;
console.log(result); // returns Infinity
如果你希望在除以零的情况下发生不同的事情,你可以使用
function divideIfNotZero(numerator, denominator) {
if (denominator === 0 || isNaN(denominator)) {
return null;
}
else {
return numerator / denominator;
}
}
答案 3 :(得分:2)
return false;
作为值来停止提交。答案 4 :(得分:1)
为什么不检查分母是否为零?
if(x != 0) z = y / x;
您还可以检查结果是否为Infinity:
3 / 0 == Infinity
true
;
(仅在镀铬中测试过。)
答案 5 :(得分:1)
希望这很有用
ods html file="test.html";
ods layout gridded
columns=2;
ods region;
proc print data=sashelp.class;
run;
ods region;
proc freq data=sashelp.class;
tables age;
run;
ods region;
proc print data=sashelp.cars;
run;
ods region;
proc freq data=sashelp.cars;
tables origin;
run;
ods layout end;
ods html close;
或您想在末尾加上的任何值。
问候。
答案 6 :(得分:0)
与停止执行略有不同,但三元运算符是一种非常灵活的自定义变量赋值方式。
var one = 1,
zero = 0,
customValue = 1;
var quotient = zero===0 ? customValue : one / zero;
这样,通过将customVariable设置为您选择的整数,可以预期在除以零时可预测的结果。
答案 7 :(得分:0)
最好的方法是上下文。但这是最简单的:
function myFunction( input ){
input = 0 ? 0.0001 : input; // same as if( input == 0 ){ input = 0.0001; }
return 1 / input;
}
基本上,如果输入为零,则在用作分母之前将其转换为非常小的数字。对于整数很有效,因为除法后,您可以将它们四舍五入。
一些注意事项阻止了这种情况的普遍性:
因此,它最适合通用,非关键情况。例如,如果您需要返回复杂计算的结果,并且不在乎答案是否精确到N位数字(由0.0001与0.00000001等确定);您只是不希望它被零除。
作为另一个答案,您还可以创建一个可重用的全局函数。
function divisor( n ){ return ( n = 0 ? 0.0001 : n ); }
function myFunction( input ){ return 1 / divisor( input ); }
可能的改进:
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; }
}
这将采用 any 值(空,数字,字符串,对象),并且如果无效或为零,则返回故障安全类零值。如果它是一个字符串并且您做的很奇怪,它也会将输出强制为一个数字。所有这些将确保您的除数功能始终有效。最后,如果您想自己处理此类错误,则可以将第二个参数设置为true并使用try/catch
。