admin管理员组

文章数量:1295954

If i need to check a parameter i do this.

if ((typeof param == 'undefined') || (param == null)){
    param = ''; //or param = false;
}

And if it's meant to be a number i might throw in a isNaN check too. I was just wondering if there were any other things i should check for or what you do if you need to check your parameters. I know javascript has a lot of quirks that could affect something like this. What is good practice to check for?

Thanks

If i need to check a parameter i do this.

if ((typeof param == 'undefined') || (param == null)){
    param = ''; //or param = false;
}

And if it's meant to be a number i might throw in a isNaN check too. I was just wondering if there were any other things i should check for or what you do if you need to check your parameters. I know javascript has a lot of quirks that could affect something like this. What is good practice to check for?

Thanks

Share edited Mar 9, 2011 at 3:33 Timothy Ruhle asked Mar 9, 2011 at 3:12 Timothy RuhleTimothy Ruhle 7,59710 gold badges44 silver badges68 bronze badges 9
  • 3 'undefined' is not the same as undefined, and use === instead of == – Dre Commented Mar 9, 2011 at 3:14
  • @Dre See what i mean, i didn't know you could do undefined without the qoutes. I picked up that from some website and didn't know there was another way to do it; or if there is a better way. – Timothy Ruhle Commented Mar 9, 2011 at 3:19
  • 1 Actually @Dre, it IS "undefined" not undefined - please see developer.mozilla/en/JavaScript/Reference/Operators/… – arnorhs Commented Mar 9, 2011 at 3:22
  • @arnorhs Oops, I did not notice the typeof there, that totally changes things. – Dre Commented Mar 9, 2011 at 3:22
  • 1 @Dre you're confusing it with if (object === undefined) - which is a whole other ball game... – arnorhs Commented Mar 9, 2011 at 3:23
 |  Show 4 more ments

2 Answers 2

Reset to default 7

Any object evaluates to false in a boolean expression if it is false, undefined, null, NaN, 0, "0", "false", or "" (the empty string).

To check for all of these at once concisely, you can just do it like this:

if(!param)

I would simply pull a cliché and say that "it depends on what you want to do"..

If you just want to make sure the value is defined and sent to the function, the code you used should be fine.

You can of course also check for elements within the arguments array, like

if (typeof arguments[0] != "string") {
    alert("Has to be string");
}

// or even

if (arguments.length < 1) {
   // there aren't any parameters
}

etc...

the arguments array is very helpful in many ways. You can also use it to overload functions - to provide different functionality or arguments depending on the number of arguments provided, etc..

But other than that, I don't know what you need.

本文标签: checking for invalid javascript function parametersStack Overflow