javascript “Try...Catch”块不适用于 parseInt()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27284948/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:16:39  来源:igfitidea点击:

"Try...Catch" Block not Working with parseInt()

javascript

提问by Fishbones

What I'm trying to do:

我正在尝试做的事情:

I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.

我有一个 javascript 程序,当单击按钮时,它会从表单中的 4 个文本框中接收 4 个字符串,然后将这些字符串输出到格式化的 textarea 中。

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);
}

The above code works just fine, and does exactly what I want it to do for the scope of my program.

上面的代码工作得很好,并且在我的程序范围内完成了我想要它做的事情。

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!");
    }
}

What I'm trying to accomplish with the try...catch block is simply to make sure that

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

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

are actually numbers.

实际上是数字。

The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!

每次我运行程序时都会触发 try...catch 语句,并且不关心我在相应的文本框中输入了什么。我将不胜感激对此的任何和所有见解!

Also: I looked at both of these links and was unable to understand my problem. javascript parseInt return NaN for empty stringhttp://www.w3schools.com/jsref/jsref_isnan.asp

另外:我查看了这两个链接,但无法理解我的问题。 javascript parseInt 为空字符串返回 NaN http://www.w3schools.com/jsref/jsref_isnan.asp

回答by jfriend00

Your root problem here is that isNaN()tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.

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

You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()

您可以在此处查看测试是否可以将某些内容解析为有效数字的方法:在 JavaScript 中验证十进制数字 - IsNumeric()

It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:

值得阅读那里的好答案中的细节,但归结为这样的事情,这比您需要的要多一些,但具有通用性:

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

And, then there's no reason to use exceptions in your code, so you can just do this:

而且,没有理由在您的代码中使用异常,所以您可以这样做:

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


Also, in your code, some .Valueproperties look like maybe they should be .value(lowercase).

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

回答by Leo

In your first code block

在你的第一个代码块中

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

You are using Value, which should be value, that's case-sensitive.

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

By the way, isNaNreturns boolean, you don't have to compare with true

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