zoukankan      html  css  js  c++  java
  • js类型判断

    判断数组

    let arr = []
    
    Array.isArray(arr)
    // true
    
    arr.constructor === Array
    // true
    
    Object.prototype.toString.call(arr)
    // "[object Array]"
    
    typeof 判断对象或者数组或者null都为"object" 
    

    判断对象

    let obj = {}
    
    Object.prototype.toString.call(obj)
    // "[object Object]"
    
    obj.constructor === Object
    // true
    
    instanceof  判断对象和数组都为true
    

    判断函数

    function fn(){
    	console.log('hello world')
    }
    
    Object.prototype.toString.call(fn)
    // "[object Function]"
    

    不同数据类型的Object.prototype.toString方法返回值如下。

    数值:返回[object Number]。
    字符串:返回[object String]。
    布尔值:返回[object Boolean]。
    undefined:返回[object Undefined]。
    null:返回[object Null]。
    数组:返回[object Array]。
    arguments 对象:返回[object Arguments]。
    函数:返回[object Function]。
    Error 对象:返回[object Error]。
    Date 对象:返回[object Date]。
    RegExp 对象:返回[object RegExp]。
    其他对象:返回[object Object]。
    

    扩展数据类型判断函数

    function myTypeOf(v){
    	var str = Object.prototype.toString.call(v);
    	var reg = /[object (.*?)]/;
    	return str.match(reg)[1].toLowerCase();
    }
    
    myTypeOf({});
    // "object"
    
    myTypeOf([]);
    // "array"
    
    myTypeOf(myTypeOf);
    // "function"
    
    myTypeOf(null);
    // "null"
    
    myTypeOf('abc');
    // "string"
    
    myTypeOf(/reg/);
    // "regexp"
    
    myTypeOf();
    // "undefined"
    
    
    愿以往所学皆有所获
  • 相关阅读:
    php通过ip获取地理位置的方法
    python程序怎么运行起来的
    php cURL学习 一个post提交反馈的小例子
    如何运行Python程序
    python初学者的建议
    php5.4新特性实践
    php中json_encode与json_decode注意事项
    Apanta安装Emmet(Zencoding)
    office 2013 电话激活步骤
    js中encodeURI()与encodeURIComponent()区别
  • 原文地址:https://www.cnblogs.com/Azune/p/15293496.html
Copyright © 2011-2022 走看看