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"
    
    
    愿以往所学皆有所获
  • 相关阅读:
    函数模板和类模板
    Dojo常用函数
    ☆☆☆Dojo中define和declare的结合使用
    Dojo的declare接口
    Dojo的define接口
    Dojo的on函数(以前的dojo.connect)
    Dojo中的选择器
    Dojo的ready函数:dojo.ready(以前的dojo.addOnLoad)
    Dojo的dojoConfig函数
    Dojo操作dom元素的样式
  • 原文地址:https://www.cnblogs.com/Azune/p/15293496.html
Copyright © 2011-2022 走看看