判断数据类型的几种方法

在js中, 有两种数据类型,基本类型和引用类型

基本类型: Number、String、Undefined丶Boolean丶Null丶Symbol

引用类型:Array丶Object丶Function

判断类型的常用方法: 

typeof: 返回数据的数据类型,Null、Array丶Object丶Function来说,使用typeof都会统一返回object字符串

Object.prototype.toString.call(): 方法返回一个表示该对象的字符串。

3instanceof : 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型(_proto_)中, 运算符希望左操作数是一个对象,右操作数标识对象的类。如果左侧对象是右侧类的实例,则表达式返回为true,否则返回false。
 

判断numberstringundefined丶boolean的方法: 


Object.prototype.toString.call(123)         // "[object Number]"
Object.prototype.toString.call(“abc”)       // "[object String]"
Object.prototype.toString.call(undefined)   // "[object Undefined]"
Object.prototype.toString.call(true)        // "[object Boolean]"

typeof 123        // "number"
typeof ""         // "string"
typeof undefined  // "undefined"
typeof true       // "boolean"

 

判断数组的方法:

var  arr = []
Object.prototype.toString.call(arr)   //"[object Array]"
arr instanceof Array    // true
Array.isArray(arr)      //true

当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false

 

判断对象的方法:

var  obj = {}

Object.prototype.toString.call(arr)   //"[object Object]"
typeof obj   //"object" 
obj instanceof Object  // true


判断函数的方法:

var  fun = function() {  
     console.log('test')
}

Object.prototype.toString.call(fun)   //"[object Function]"
typeof fun    //"function" 
fun instanceof Function     // true
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值