GitHub 博客园 Nanakon

☀【JS】检测属性

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <script>
        var object = {
            name: null,
            sex: undefined,
            age: 0
        }
        // 不好的写法:和 null 比较
        if (object['name'] !== null) {
        } else {
            console.log('name')
        }
        // 不好的写法:和 undefined 比较
        if (object['sex'] !== undefined) {
        } else {
            console.log('sex')
        }
        // 不好的写法:检测假值
        if (object['age']) {
        } else {
            console.log('age')
        }

        // 好的写法
        if ('sex' in object) {
            console.log('sex')
        }
        // 对于所有非 DOM 对象
        // 在 IE 8 以及更早版本的 IE 中,DOM 对象并非继承自 Object,因此也不包含这个 hasOwnProperty 方法
        if (object.hasOwnProperty('sex')) {
            console.log('sex')
        }
        // 如果你不确定是否为 DOM 对象
        if ('hasOwnProperty' in object && object.hasOwnProperty('sex')) {
            console.log('sex')
        }

        var s = new String()
        console.log('split' in s)
        console.log(s.hasOwnProperty('split'))
        console.log(String.prototype.hasOwnProperty('split'))
    </script>
</body>
</html>

《编写可维护的 JavaScript》

posted on 2013-10-21 23:31  jzm17173  阅读(148)  评论(0)    收藏  举报

导航

轻音