tags:

views:

83

answers:

6
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.

+4  A: 

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

Scott Saunders
A: 

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.

duffymo
A: 

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;
}
VoY
A: 

Replace

if (strString.length == 0) {

with

if (strString == null || strString.length == 0) {
Robert Grant
+1  A: 

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);
}
Josh Stodola
A: 

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.

Luca Matteis
JavaScript function parameters are called formal parameters. Try `(function(;){}())` and you will get `SyntaxError: missing formal parameter` in the two JavaScript engines. Not sure what you'll get in ECMAScript engines like v8 and WebKit's one.
Eli Grey