4

Javascript——判断数据类型的四种方法

 2 years ago
source link: https://segmentfault.com/a/1190000040802873
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
  • 使用typeof进行判断

    语法:typeof 判断的数据
    特点:可以准确判断基本数据类型,无法对复杂数据类型进行准确判断

  • 使用constructor进行判断

    语法:对象名.constructor
    特点:只能判断复杂数据类型,不能判断基本数据类型

  • 使用instanceof进行判断

    语法:对象名 instanceof 构造函数
    特点:只能判断复杂数据类型,不能判断基本数据类型

  • 使用Object.prototype.toString.call()判断

    语法:Object.prototype.toString.call(需要判断的数据)
    特点:可以准确判断所有数据类型

  • 深度了解对象

    • 对象是数据类型的一种,以键值对的形式存储数据key : value,使用__proto__和原型链可访问自己没有的属性
    • 使用 for in循环可遍历对象身上以及原型链上所有可枚举的属性;我们可以对属性进行设置是否可枚举
    • hasOwnProperty()可以产看是否是自己的属性
      语法:对象名.hasOwnProperty('需要检测的属性名')
    • defineProperty()数据劫持
      一种给对象添加属性的方式,可以对属性设置各种各样的行为状态
      语法:Object.defineProperty(需要添加属性的对象, key, {添加怎么样的设置})
  <input id="username"  type="username">
  <script>
    let prop = {
      firstName: '张',
      lastName: '思锐'
    }
    let obj = {}

    Object.defineProperty(obj, 'username', {
      enumerable: true,// 设置属性是否可枚举
      get() {
        // 数据劫持prop属性
        return prop.firstName + prop.lastName
      },
      // val形参接收外界传过来的值
      set(val) {
        // 接收 形参进行修改 属性值内容
        let a = val.slice(0, 1)
        let b = val.slice(1)
        // 使用劫持到的属性进行设置
        prop.firstName = b
        prop.lastName = a
        let inp = document.querySelector('#username')
        inp.value = obj.username
      }
    })
    obj.username = '张一山'
  </script>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK