Check if a object is defined, best practice.

前端 未结 4 772
滥情空心
滥情空心 2020-12-15 17:04

I have the following JSON response from a ajax-request.

var json = {
    \"response\": {
        \"freeOfChargeProduct\": {  
        \"description\": \"Prod         


        
4条回答
  •  离开以前
    2020-12-15 17:43

    if(x && typeof x.y != 'undefined') {
        ...
    }
    
    // or better
    function isDefined(x) {
        var undefined;
        return x !== undefined;
    }
    
    if(x && isDefined(x.y)) {
        ...
    }
    

    This will work for any data type in JavaScript, even a number that is zero. If you are checking for an object or string, just use x && x.y within the if statement, or if you already know that x is an object, if(x.y) ...

提交回复
热议问题