zoukankan      html  css  js  c++  java
  • 数据类型的判断 --Object.prototype.toString.call(obj)精准检测对象类型

    数据类型的判断 typeof

    typeof返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、symbol、object、undefined、function等7种数据类型,但不能判断null、array等

    typeof Symbol();  // symbol 有效
    typeof '';  // string 有效
    typeof 1;  // number 有效
    typeof true;  //boolean 有效
    typeof undefined;  //undefined 有效
    typeof new Function();  // function 有效
    typeof null;  //object 无效
    typeof [] ;  //object 无效
    typeof new Date();  //object 无效
    typeof new RegExp();  //object 无效
    

    数据类型的判断 instanceof

    instanceof 是用来判断A是否为B的实例,表达式为:A instanceof B,如果A是B的实例,则返回true,否则返回false。instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,但它不能检测null 和 undefined

    [] instanceof Array; //true
    {} instanceof Object;//true
    new Date() instanceof Date;//true
    new RegExp() instanceof RegExp//true
    null instanceof Null//报错
    undefined instanceof undefined//报错
    

    严格运算符===

    只能用于判断null和undefined,因为这两种类型的值都是唯一的。

    constructor

    constructor作用和instanceof非常相似。但constructor检测 Object与instanceof不一样,还可以处理基本数据类型的检测。
    细节问题

    1. null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。
    2. 函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的constructor 引用会丢失,constructor 会默认为 Object

    Object.prototype.toString.call()

    Object.prototype.toString.call('') ;   // [object String]
    Object.prototype.toString.call(1) ;    // [object Number]
    Object.prototype.toString.call(true) ; // [object Boolean]
    Object.prototype.toString.call(undefined) ; // [object Undefined]
    Object.prototype.toString.call(null) ; // [object Null]
    Object.prototype.toString.call(new Function()) ; // [object Function]
    Object.prototype.toString.call(new Date()) ; // [object Date]
    Object.prototype.toString.call([]) ; // [object Array]
    Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
    Object.prototype.toString.call(new Error()) ; // [object Error]
    
  • 相关阅读:
    IE浏览器下报错: strict 模式下不允许一个属性有多个定义
    Vue 做的项目在IE下面打开一片空白解决方法
    小程序如何动态修改标题navigationBarTitleText
    小程序-for循环遍历的使用
    vue项目-打印页面中指定区域的内容(亲测有效!)
    vue省市区三级联动(高仿京东)
    vue-父组件向子组件传值
    Sea.js 手册与文档
    angular之模块开发二
    angular之跨域
  • 原文地址:https://www.cnblogs.com/whkl-m/p/10670402.html
Copyright © 2011-2022 走看看