zoukankan      html  css  js  c++  java
  • 通过 Object.prototype.toString.call() 进行类型判断

    首先看一段ECMA中对Object.prototype.toString的解释: Object.prototype.toString( ) When the toString method is called, the following steps are taken: 1. Get the [[Class]] property of this object. 2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
    3. Return Result (2)
    我们知道,Javascript中,一切皆为对象。所以如下代码,应当会输出对应字符:01varoP = Object.prototype,02toString = oP.toString;03 04console.log(toString.call([123]));//[object Array]05console.log(toString.call('123'));//[object String]06console.log(toString.call({a: '123'}));//[object Object]07console.log(toString.call(/123/));//[object RegExp]08console.log(toString.call(123));//[object Number]09console.log(toString.call(undefined));//[object Undefined]10console.log(toString.call(null));//[object Null]11//.... 标准浏览器中完美的作到,但是(为什么要说但是呢)IE6中,却会出现以下问题:通过Object.prototype.toString.call获取的 字符串,undefined,null均为Object
    所以,我们又要悲剧的先对以上类型进行判断,完整代码:view sourceprint?01varoP = Object.prototype,02toString = oP.toString;03 04functiontypeOf(value) {05    if(null=== value) {06        return'null';07    }08 09    vartype = typeofvalue;10    if('undefined'=== type || 'string'=== type) {11        returntype;12    }13 14    vartypeString = toString.call(value);15    switch(typeString) {16    case'[object Array]':17        return'array';18    case'[object Date]':19        return'date';20    case'[object Boolean]':21        return'boolean';22    case'[object Number]':23        return'number';24    case'[object Function]':25        return'function';26    case'[object RegExp]':27        return'regexp';28    case'[object Object]':29        if(undefined !== value.nodeType) {30            if(3 == value.nodeType) {31                return(/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';32            } else{33                return'element';34            }35        } else{36            return'object';37        }38    default:39        return'unknow';40    }41}
  • 相关阅读:
    vue项目总结,所用到的技术点
    豆瓣电影个人项目总结
    博学谷项目总结,个人总结经验
    JavaScript数组的常用方法
    移动端base.css的内容,
    normalize.css可以对css初始化,不同浏览器可以统一初始样式
    jsp第十次作业
    jsp第九次作业
    jsp第八次作业
    jsp第七次作业
  • 原文地址:https://www.cnblogs.com/danghuijian/p/4400057.html
Copyright © 2011-2022 走看看