I'm doing my calculator and want prevent div to zero. I guess I must check last to elements if they are "/0"? what I'm doing wrong?
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
//alert(input.value[lastElement-1]);
//alert(input.value[lastElement]);
if (input.value[lastElement-1] === "/")
{
if (input.value[lastElement] === "0")
{
alert(" / to Zero");
}
}
}
答案 0 :(得分:0)
Use RegEx instead:
var is_div_by_zero = /\/[\s.0]+$/.test(value); // Returns true if it is divided by zero, false if otherwise
It matches:
As T.J. Crowder commented it is probably due to inconsistent formatting.
答案 1 :(得分:0)
It would be better to work with the Javascript engine instead of going against it.
Just evaluate the entered formula and handle the exceptions thrown by the Javascript engine.
Place your evaluation code inside a try ... catch(e)
block and handle the exceptions there.
try {
// your calculation code here, eg:
result = value1 / value2;
} catch (e) {
// this catches the error and provides the proper way of handling the errors,
// and your script doesn't die because of the error
// also, the e parameter contains the exception thrown, which provides info you can
// display
// or based on the error type come up with a proper solution
alert (e.message);
}
More info on Javascript error handling: http://javascript.info/tutorial/exceptions
Update
Forgot that, unfortunately, a division by zero does not result in an exception being thrown in Javascript. It will result in NaN
for 0/0 and Infinity
for x/0
(where x
is any number). Infinity
has the type number
.
You can test for this after evaluating your equation.
答案 2 :(得分:0)
我之前的回答是解决您问题的方法,但对于您希望实现的目标而言可能过于复杂。
不要逐个从输入字符中取出东西,而是将字符串拆分到操作符上并修剪部分。我将为两个操作数创建解决方案,您可以从那开始。
var equation = document.getElementById("t").value;
var operands = equation.split('/');
var divisor = operands[operands.length - 1].trim();
// since the contents of your input are a string, the resulting element is also a string
if (parseFloat(divisor) == 0) {
alert("Division by zero");
}
这是一种非常粗略的方法,因为您必须验证并过滤您的输入(除了数字和有效运算符之外,不应该允许其他任何事情)。此外,您还必须检查操作优先级(您在等式中是否允许多个运算符?)等。