简体   繁体   English

为什么此JS代码失败?

[英]Why does this JS code fail?

259 function isNumeric(strString) { 
260 var strValidChars = "0123456789";
261 var strChar;
262 var blnResult = true;
263
264 if (strString.length == 0) {
265 return false;
266 }
267
268 // Test strString consists of valid characters listed above
269 for (i = 0; i < strString.length && blnResult == true; i++)
270 {
271 strChar = strString.charAt(i);
272 if (strValidChars.indexOf(strChar) == -1)
273 {
274 blnResult = false;
275 }
276 }
277 return blnResult; 
278 }

Firefox crashes on line 264 with the following message: Firefox在第264行崩溃,并显示以下消息:

strString is undefined strString未定义

Why does this code fail? 为什么此代码失败? strString is a formal parameter of the isNumeric function, so it should always be defined. strString是isNumeric函数的形式参数,因此应始终对其进行定义。

调用函数的代码未提供该变量的定义值。

Re-create the error like so... 像这样重新创建错误...

javascript:alert(isNumeric(undefinded));

And fix it like so... 然后像这样修复它...

function isNumeric(strString) {   
  strString = strString + "";

But why not use a regular expression? 但是,为什么不使用正则表达式呢?

function isNumeric(val) {
  return /^[0-9]+$/.test(val);
}

我不确定,但是看一下函数,我会说这是正则表达式的最佳选择。为什么不使用它呢?它看起来比从Code Toad中获得的功能还强大。

You are probably passing an undefined value to your function from the calling code. 您可能正在从调用代码向函数传递未定义的值。 The length property is only defined for strings and arrays, therefore the error message. length属性仅为字符串和数组定义,因此会出现错误消息。 You could test for undefined like this: 您可以像这样测试未定义的内容:

if (typeof strString == "undefined") {
    return false;
}

Replace 更换

if (strString.length == 0) {

with

if (strString == null || strString.length == 0) {

Why do you say it's a formal paramater ? 为什么说这是正式的参数

JavaScript is very flexible with parameters; JavaScript具有非常灵活的参数。 it doesn't throw any warnings when the number of parameters you pass are different from the definition. 当您传递的参数数量与定义数量不同时,它不会发出任何警告。 This is rather flexible but also confusing for people that come from a C/C++ background. 这是相当灵活的,但是对于来自C / C ++背景的人来说也很混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM