首页 > 技术文章 > 判断是否存在某个字段hasOwnProperty

ch-zaizai 2018-04-12 14:52 原文

<script type="text/javascript">

        var obj = {
            a: 1,
            fn: function(){
 
            },
            c:{
                d: 5
            }
        };
        console.log(obj.hasOwnProperty('a'));//true
        console.log(obj.hasOwnProperty('fn'));//true
        console.log(obj.hasOwnProperty('c'));//true
        console.log(obj.c.hasOwnProperty('d'));//true
        console.log(obj.hasOwnProperty('d'));//false, obj对象没有d属性
        var str = new String();
        console.log(str.hasOwnProperty('substring'));//false
        console.log(String.prototype.hasOwnProperty('substring'));//true
    </script>

推荐阅读