admin管理员组

文章数量:1291280

I created an isset function to check if a variable is defined and not null. Here's my code:

isset = function(a) {
    if ((typeof (a) === 'undefined') || (a === null))
        return false;
    else
        return true;
};
var a = [];

// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined

Any suggestion to make my function work for test 2? Thanks.

I created an isset function to check if a variable is defined and not null. Here's my code:

isset = function(a) {
    if ((typeof (a) === 'undefined') || (a === null))
        return false;
    else
        return true;
};
var a = [];

// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined

Any suggestion to make my function work for test 2? Thanks.

Share Improve this question asked Feb 14, 2012 at 9:43 Tamás PapTamás Pap 18.3k15 gold badges73 silver badges104 bronze badges 3
  • typeof is an operator not a function, you should get rid of the () around the values you are testing with it. – Quentin Commented Feb 14, 2012 at 9:51
  • @Quentin: it's arguable, some prefer to use parenthesis for all control statements to make the code more consistent and readable. For instance, some prefer to write return (true) instead of return true. It's a matter of preferences (and irrelevant to the question). – haylem Commented Feb 14, 2012 at 9:58
  • possible duplicate of Javascript isset() equivalent – Gajus Commented Nov 18, 2014 at 7:55
Add a ment  | 

4 Answers 4

Reset to default 4

You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:

alert(isset(a['not']) && isset(a['not']['existent']));

that won't work, and you can't make it work. what happens is this: the js engine tries to evaluate a['not'] and get's "undefined", then it tries to evaluate the property 'existent' of the undefined and you get that error. all of that happens before the call to your function...

what you can do is something like:

var isset = function(obj, props) {
    if ((typeof (obj) === 'undefined') || (obj === null))
        return false;
    else if (props && props.length > 0)
        return isset(obj[props.shift()], props);
    else
        return true;
};

then you call it like this:

var a = [];

// Test 1
alert(isset(a, ['not']);
// Test 2
alert(isset(a, ['not', 'existent']));

(**this just a pseudo code, you might need to modify it a bit to actually work)

Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.

Well, You can do right this:

1) as we do in php:

$vara = "abc";
$a =0;

 while(isset($vara[a]){
a++;
} 

2) as I do in javascript:

vara = "abc";
 while (vara[a] != null){
a++;
}

本文标签: Javascript isset functionStack Overflow