How do I check if a string/array/object exists in Javascript?

This question already has an answer here:

  • How do I check if an object has a property in JavaScript? 22 answers

  • if(data != void(0) && data.unavailableItems != void(0)){
      //exists
    }
    

    正如Norman在评论中指出的,你应该检查void 0意味着什么


    A good tool to use for checking if an object contains a property is obj.hasOwnProperty(prop)

    if(data.hasOwnProperty("unavailableItems")){
    
    }
    

    Also note, that a shim is available from John Resig for obj.hasOwnProperty

    function hasOwnProperty(obj, prop) {
     var proto = obj.__proto__ || obj.constructor.prototype;
     return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
    }
    
    if ( Object.prototype.hasOwnProperty ) {
     var hasOwnProperty = function(obj, prop) {
        return obj.hasOwnProperty(prop);
     }
    }
    
    链接地址: http://www.djcxy.com/p/27310.html

    上一篇: 即在循环中使用javascript,在循环中使用chrome

    下一篇: 如何检查Javascript中是否存在字符串/数组/对象?