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]';
}

我会接着补充的。。。。

转载于:https://www.cnblogs.com/zhangkunweb/p/5646648.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值