zoukankan      html  css  js  c++  java
  • js 类型检测

    1、检测字符串、数值、布尔值、undefined、function 使用typeof(在Safari和Chrome中检测正则也会返回 "function")

    2、检测null 应用“===”

    3、检测其它对象:

          方法一:利用instanceof/constructor  

          (再某些ie版本中存在跨iframe问题,每个iframe下都有自己的一套原型链,跨frame实例化的对象彼此是不共享原型链)

    alert(A  instanceof  Object)
    alert(A  instanceof  Array)
    alert(A  instanceof  RegExp)  
    alert(A.constructor==Array)
          例如:

          方法二:利用 Object.prototype.toString.call()  

          (解决了方法一跨iframe 失效的问题)

          例如:

    Object.prototype.toString.call ({})          //"[objectObject]"
    Object.prototype.toString.call ([1,2,3,4]);  //"[objectArray]"
    Object.prototype.toString.call(newDate());   //"[objectDate]"
    Object.prototype.toString.call(/^hello/);    //"[objectRegExp]"
    Object.prototype.toString.call(newError())   //"[objectError]"
    Object.prototype.toString.call(newNumber())  //"[objectNumber]"

          参考jquery解决方案

        var class2type = {};
        $.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) {
            class2type[ "[object " + name + "]" ] = name.toLowerCase();
        });
        $.type = function (obj) {
            return obj == null ?
                String(obj) : class2type[ toString.call(obj) ] || "object"
        };

           另外,ECMAScript 5 定义了一个新方法Array.isArray(),该函数在参数为数组时返回true,例如

           Array.isArray([])     // true

           所以我们可以定义:  

    if(typeof Array.isArray=="undefined"){
       Array.isArray=function(obj){
           return Object.prototype.toString.call(obj)==="[object Array]";
       }
    }


  • 相关阅读:
    PAT (Advanced Level) Practice 1054 The Dominant Color (20 分)
    PAT (Advanced Level) Practice 1005 Spell It Right (20 分) (switch)
    PAT (Advanced Level) Practice 1006 Sign In and Sign Out (25 分) (排序)
    hdu 5114 Collision
    hdu4365 Palindrome graph
    单链表查找最大值、两个递增的链表合并并且去重
    蓝桥杯-最短路 (SPFA算法学习)
    蓝桥杯-最大最小公倍数
    Codeforces-470 div2 C题
    蓝桥杯-地宫取宝
  • 原文地址:https://www.cnblogs.com/hdchangchang/p/3965344.html
Copyright © 2011-2022 走看看