What you have won't work for undefined. You can have a property named "undefined"
, but that's a string name, not the actual undefined
value. You may get a match via type conversion, but it will also match if you have a string named "undefined"
too which is not something you want.
I would suggest a more explicit test that uses ===
to avoid any type conversions. There are several ways to do it that are slightly less verbose than what you had:
if (myParam === null || myParam === undefined ||
(myParam && myParam.length == 1 && "1a*@ ".indexOf(myParam) !== -1) {
// code here
}
Or you can make an array and your own cross browser function (or use a polyfill for Array.indexOf()
to search an array which can hold all the values:
function inArray(val, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] === val) {
return(true);
}
}
return(false);
}
var testValues = [null, undefined, "1", "a", "*", "@", " "];
if (inArray(window.lala, array)) {
// your code here
}
You can use the object form you were experimenting with and just use explicit tests for null
and undefined
, but I think the string.indexOf()
suggestion in my first proposal is simpler. Anyway, here's a safe form using the object
if (myParam === null || myParam === undefined ||
(myParam && (myParam in {"*":0, "1":0, "a":0, "@":0, " ":0})) {
// code here
}
My recommendation would be the first option as I think it's the cleanest and it's also really easy to extend by just adding more chars to the test string.