开发者

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:

strString is undefined开发者_如何学编程

Why does this code fail? strString is a formal parameter of the isNumeric function, so it should always be defined.


The code calling your function is not providing a defined value for that variable.


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


I"m not sure, but looking at what the function does I'd say this is the perfect spot for a regular expression. Why aren't you using one? It looks more capable than the function you took from 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. 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; 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜