"的try ... catch"阻止不使用parseInt()

时间:2014-12-04 01:52:58

标签: javascript

我正在尝试做什么:

我有一个javascript程序,当点击一个按钮时,从一个表单中的4个文本框中获取4个字符串,并将这些字符串输出到格式化的文本区域。

function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = "   ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d + 
              "Item Name: " + form.Item_Name.value + d + 
              "Item Cost: " + form.Item_Cost.value + d + 
              "Quantity: " + form.Quantity.value + '\n';


document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value =  document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}

上面的代码运行得很好,并且正是我希望它为我的程序范围做的事情。

try {
    if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
        throw "Error1";
    }
} catch (e) {
    if (e == "Error1") {
        alert("Error! You must enter a number into the qty and cost fields!");
    }
}

我试图用try ... catch块来完成的只是为了确保

document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value

实际上是数字。

每次运行程序时,try ... catch语句都会触发,而不关心我放在相应文本框中的内容。我非常感谢对此的任何见解!

另外:我查看了这两个链接,但无法理解我的问题。 javascript parseInt return NaN for empty string http://www.w3schools.com/jsref/jsref_isnan.asp

2 个答案:

答案 0 :(得分:6)

这里的根问题是isNaN()测试以查看值是否为NaN。它不会测试字符串是否是正确的数字。它有一些强制规则来尝试处理字符串,但这实际上不是它的设计目的。

您可以在此处查看测试某些内容是否可以解析为有效数字的方法:Validate decimal numbers in JavaScript - IsNumeric()

值得阅读那里的好答案中的详细信息,但它可以归结为这样的东西比你需要的更多,但是是通用的:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

然后,没有理由在代码中使用异常,所以你可以这样做:

if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
   alert("Error! You must enter a number into the qty and cost fields!");
}

此外,在您的代码中,某些.Value属性看起来可能应该是.value(小写)。

答案 1 :(得分:0)

在您的第一个代码块中

var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);

您使用的Value应该是value,区分大小写。

顺便说一句,isNaN返回布尔值,您不必与true进行比较