javascript数据类型检测方法

一、字符串、数字、布尔值、undefined的最佳选择市使用 typeof 运算符进行检测:

  • 对于字符串,typeof 返回"string"
  • 对于数字,typeof 返回"number"
  • 对于布尔值,typeof 返回"boolean"
  • 对于undefined,typeof 返回"undefined"

用法:typoef variable 或 typeof(variable)

 

二、null 判断

  由于 typeof null 返回的值为 "object"(这是一个被诟病的语言本身设计存在的BUG),我们不能使用 typeof 来对 一个变量值是否为 null 进行判断。此外我们一般不建议将变量与 null 进行比较。

不好的写法:

if( item !== null ) {
  // 执行一些逻辑......
}

除非在你能预见该变量有可能等于 null 的情况下,你才可以使用恒等运算符(===)和非恒等运算符(!==)进行比较:

var ele = document,getElementById("box");
if( ele === null ) { // 执行一些逻辑...... }

三、数组、对象与函数的检测

1. 数组,由于数组属于引用类型,并且使用 typeof 对其进行检测返回的值为"object",在无法使用 typeof 判断的情况下,最佳的解决方案如下:

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

2. 函数,虽然函数也属于引用类型,但因为 typeof 对函数检测的返回值为"function",因此检测函数的最好方案是使用 typeof :

function func() {}

typeof func === "function" // true

陷阱:在 IE8 及 IE8 以下中使用 typeof 对DOM 节点中的方法检测会返回"object",因此在该场景下的替换方案为:

// IE8及IE8以下
console.log( typeof document.getElementById ); // "object"

// 替换方案
if( "getElementById" in document ) {
    //执行逻辑......
}

3. 自定义对象和内置对象,由于 typeof 对所有引用类型数据都返回"object"(函数除外),因此我们一般使用 instanceof 来判断其属于哪种引用类型:

(跨frame使用会出现问题,因为每个文档都有各自的内置对象Object、Date、Function等)

var obj = {}
console.log( obj instanceof Object ); // true

function Person (name) {
    this.name = name
}

var person = new Person("Jack");
console.log( person instanceof Person ); // true

var time = new Date();
console.log( time instanceof Date ); // true

 

posted @ 2014-04-21 22:03  白牙青森  阅读(377)  评论(0编辑  收藏  举报