javascript 判断参数类型大全

js 判断类型的在开发中是很常用的,因为js 是弱类型的语言,var 可以接受任何形式的类型,但是在真正的开发中,我们需要根据不同类型做不同的处理,所以这个是必须的精通。

首先需要知道 typeof这个方法 了解可以看看http://www.cnblogs.com/lidabo/archive/2011/12/29/2305770.html

1.判断Object类型  isObject(arg)

根据了解,对象、数组、null 返回的值是 object,那么只要把null排除就可以了。

1 function isObject(value) {
2     return value !== null && typeof value === 'object';
3 }

2.判断Number类型  isNumber(arg) 

判断number 用 typeof()  就可以实现 

function isNumber(value) {return typeof value === 'number';}

3.判断String类型  isString(arg)

判断string 用 typeof() 就可以实现

function isString(value) {return typeof value === 'string';}

4.判断 undefined和defined   isUndefined(arg) 和 isDefined(arg)

function isUndefined(value) {return typeof value === 'undefined';}

function isDefined(value) {return typeof value !== 'undefined';}

5.判断blankObject类型  isBlankObject(arg)

function isBlankObject(value) {
   return value !== null && typeof value === 'object' && !Object.getPrototypeOf(value);
}

6.判断function 类型 isFunction(arg)

function isFunction(value) {return typeof value === 'function';}

7.判断boolean类型 isBoolean(arg);

function isBoolean(value) {
  return typeof value === 'boolean';
}

上面的是用typeof() 完成的类型判断,但是他不能判断Date ,RegExp Array,File等; 那么用什么方法呢?

当我看到这么一句话,恍然大悟:利用 Object.prototype.toString.call 得到 [[class]]

看看这句英文

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)

其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将 “[object,获取的类名]” 组合后并返回。

那么我们接着判断类型。。。。

8.判断Date类型  isDate(arg)

function isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]';
}

9.判断RegExp 类型  isRegExp(arg)

function isRegExp(value) {
     return Object.prototype.toString.call(value) === '[object RegExp]';
}

10.判断Array 类型 isArray(arg)

function isArray(value) { 
    return Object.prototype.toString.call(value) === '[object Array]';  
}

11.判断 File 类型 isFile(arg)

function isFile(obj) {
  return Object.prototype.toString.call(obj) === '[object File]';
}

我会接着补充的。。。。

posted @ 2016-07-06 13:49  zhanglearning  阅读(889)  评论(0编辑  收藏  举报