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.开发者_JAVA百科 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
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.
精彩评论