js类型判断的方式总结

js类型判断的方式总结

1.typeof

typeof 可以用来判断 string ,number ,boolean,undefined,symbol但是无法判断null ,返回为object ,判断数组和对象的值均为object

typeof(1)             // number
typeof('jianshu')     // string
typeof(true)          // boolean
typeof(undefined)     // undefined
typeof(null)          // object
typeof([])            // object
typeof({})            // object
  1. instanceof

instanceof运算符希望左操作数是一个对象,右操作数标识对象的类。如果左侧的对象是右侧类的实例,则表达式返回true;否则返回false。

let  d = new Date()
d instanceof Date     // true  
d instanceof Object   // true  所有类都是Object的父类
d instanceof Number    // false
let arr = [1,2,3]
arr instanceof Array  // true
null instanceof Object  // false
  1. Object.prototype.toString.call()

    判断对象所属类 。提取返回字符串的倒数第八个到倒数第二个位置。

    Object.prototype.toString.call(null)    // "[object Null]"
    Object.prototype.toString.call(null).slice(8,-1)  // Null
    Object.prototype.toString.call(1).slice(8,-1)     // Number
    Object.prototype.toString.call(window).slice(8,-1)   //Window 客户端宿主对象
    
    
  2. Array.isArray()

    ​ 用来判断是否为数组。

    Array.isArray([1,2,3])     // true
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容