GitHub 博客园 Nanakon

↗☻【编写可维护的JavaScript #BOOK#】第8章 避免“空比较”

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div class="box"></div>
    <div class="box" id="box2"></div>
    <script src="http://static01.baomihua.com/js/lib/jquery-1.4.4.min.js"></script>
    <script>
        'use strict'

        // 5种原始类型:字符串、数字、布尔值、null和undefined
        console.log(typeof '' === 'string') // 字符串
        console.log(typeof 5 === 'number') // 数字
        console.log(typeof true === 'boolean') // 布尔值
        console.log(typeof a === 'undefined') // undefined

        var element = document.getElementById('box1')
        var element2 = document.getElementById('box2')
        console.log(element === null) // null

        console.log(document.getElementById('box2').className === 'box')
        console.log($('#box2')[0].className === 'box')
        console.log($('.box')[$('.box').length - 1].className === 'box')
        console.log($('#box3').length === 0)
        console.log(typeof $('#box3')[0] === 'undefined')
        console.log(typeof [][0] === 'undefined')

        // 引用值:Object、Array、Date、Error
        console.log(typeof null === 'object')
        var now = new Date()
        console.log(now instanceof Date) // Date
        console.log(/a/ instanceof RegExp) // RegExp

        function Person(name) {
            this.name = name
        }
        var me = new Person('Nicholas')
        console.log(me instanceof Person)
        console.log(typeof Person === 'function') // function
        function isArray(value) {
            if (typeof Array.isArray === 'function') {
                return Array.isArray(value)
            } else {
                return Object.prototype.toString.call(value) === '[object Array]'
            }
        }
        console.log(isArray([])) // array

        var object = {
            count: 0,
            related: null
        }
        if ('count' in object) { // 属性
            console.log('ca')
        }
        if (me.hasOwnProperty('name')) { // 实例属性
            console.log('ca')
        }
        if ('hasOwnProperty' in element2 && element2.hasOwnProperty('name')) { // IE8以及更早版本的IE中,DOM对象并非继承自Object,因此也不包含这个方法
            console.log('ca')
        }
    </script>
</body>
</html>

 

posted on 2013-08-17 16:38  jzm17173  阅读(159)  评论(0)    收藏  举报

导航

轻音