javascript 判断数据类型

https://www.cnblogs.com/starof/p/6368048.html

JavaScript基本类型和引用类型是不同的
基本类型:Undefined、Null、Boolean、Number、String
按值传递

var a=1
var b=a
b=2
a
1

引用类型:

var a=new Object()
var b=a
b.x=1
a
{x: 1}

typeof不能判断array
instanceof 判断继承
Object.prototype.toString.call(x)比较全能,但IE有限

typeof
对一个值使用typeof操作符可能返回下列某个字符串:

“undefined” —— 如果这个值未定义;
“boolean” —— 如果这个值是布尔值;
“string” —— 如果这个值是字符串;
“number” —— 如果这个值是数值;
“object” —— 如果这个值是对象或 null;
“function” —— 如果这个值是函数。
注意:

typeof是一个操作符而不是函数,所以typeof后面的圆括号可加可不加。
调用typeof null会返回 “object”,因为特殊值null被认为是一个空的对象引用。Safari 5 及之前版本、Chrome 7 及之前版本在对正则表达式调用typeof操作符时会返回 “function”,而其他浏览器在这种情况下会返回 “object”。
我们无法区分对象,数组和null,因为这三者的返回值都是 “object”。

instanceof
其语法如下所示:
result = variable instanceof constructor
exp: console.log(person instanceof Object) // 变量person是Object 吗?
注意:
instanceof只能检测引用类型,所以在判断基本类型的值时始终会返回 false,例如1 instanceof Number => false。

Object.prototype.toString.call
Object.prototype.toString.call是最安全可靠的检测方式,因为我们调用的是Object上的原生的toString()方法。

其实js 里面还有好多类型判断,如[object HTMLDivElement] == div 对象、[object HTMLBodyElement] == body 对象、还有object Document或者object HTMLDocument …各种dom节点的判断,这些东西在我们写插件的时候都会用到。

我们可以做以下的类型判断封装(前提是Object.prototpye.toString是未被修改过的原生版本):

var gettype = Object.prototype.toString
var  util = {
    isObj: function(o) {
        return  gettype.call(o)=="[object Object]";
    },
    isArray: function(o) {
        return  gettype.call(o)=="[object Array]";
    },
    isNull:function(o) {
        return  gettype.call(o)=="[object Null]";
    },
    isDocument: function(o) {
        return  gettype.call(o)=="[object Document]"|| [object HTMLDocument];
    },
    isFunction: function (o) { 
        return Object.prototype.toString.call(0) == "[object Function]"; 
    },
    isRegExp: function(o) { 
        return Object.prototype.toString.call(0) == "[object RegExp]"; 
    },
    isJson: function(o) {
        return !!(window.JSON && Object.prototype.toString.call(JSON) == "[object JSON]";);
    },
    ........
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值