recognizing undefined object name/value pairs

This question already has an answer here:

  • Detecting an undefined object property 40 answers

  • 您应该使用typeof来检查未定义的密钥。

       function parseMe(data){
    
            renderR="";
    
            if(data[0].item4!="collapse"){
    
                renderR=data[0].item4; 
                //if name/value pair isn't equal to "collapse" render it.
    
            }else if(typeof data[0].item4==="undefined"){ 
    
                document.getElementById('div1').style.display='none'; 
                //if name/value pair is undefined in object hide the div.
    
            } 
    }
    

    As noted in the comments above, the else if condition could be changed to typeof(...) === 'undefined' to make the method work. A more standard solution, however is to query the object's key values using the hasOwnProperty method, eg

    } else if (data[0].hasOwnProperty('item4')) {

    This check should really be done first off, before attempting to access the property via the dot notation or square braces. Furthermore, this will not traverse the prototype chain to determine inherited attributes but it will detect any attribute directly belonging to the object, which should be sufficient for raw object values and parsing logic such as this. So a final solution that includes restructuring of the code could either use the hasOwnProperty method or use the in operator and a switch statement, eg

    for (var key in data[0]) {
        var value = data[0][key];
        switch (key) {
            case "item1":
                dosomething(value);
                break;
            case "item2":
                dosomethingelse(value);
                break;
            // etc...
        }
    }
    
    链接地址: http://www.djcxy.com/p/22646.html

    上一篇: 如何声明一个未定义的变量?

    下一篇: 识别未定义的对象名称/值对