首页 技术 正文
技术 2022年11月12日
0 收藏 472 点赞 4,187 浏览 1846 个字

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

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

1.判断Object类型  isObject(arg)

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

 function isObject(value) {
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]';
}

我会接着补充的。。。。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,991
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,506
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,349
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,134
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,766
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,844