数据类型判断

数据类型判断


① typeof:

typeof {} // object
typeof  [1,2] // object


判断数据类型,返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
使用typeof判断变量是否存在(如if(typeof a!="undefined"){...});
Typeof 运算符的问题是无论引用的对象是什么类型,它都返回object;

 ②instanceof:

  判断已知对象类型的方法,instanceof 后面一定要是对象类型,并且大小写不能错,这个方法适合一些条件选择或分支。

var c= [1,2,3];
console.log(c instanceof Array) //true
// 要判断的变量 instanceof 数据类型
// 如果类型正确 返回true

③根据对象的contructor属性判断:


console.log('数据类型判断' -  constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true

④使用Object.prototype.toString.call()检测对象类型(是对象的一个原生原型扩展函数,用来更精确的区分数据类型):


var gettype=Object.prototype.toString
gettype.call('aaaa') 输出 [object String] 
gettype.call(2222) 输出 [object Number] 
gettype.call(true) 输出 [object Boolean] 
gettype.call(undefined) 输出 [object Undefined] 
gettype.call(null) 输出 [object Null] 
gettype.call({}) 输出 [object Object] 
gettype.call([]) 输出 [object Array] 
gettype.call(function(){}) 输出 [object Function]

⑤万能的方法:jquery.type()(如果对象是undefined或null,就返回相应的“undefined”或“null”):


jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined"
jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"
如果对象有一个内部的[[Class]]和一个浏览器的内置对象的 [[Class]] 相同,我们返回相应的 [[Class]] 名字。 (有关此技术的更多细节。 )
jQuery.type( true ) === "boolean"
jQuery.type( 3 ) === "number"
jQuery.type( "test" ) === "string"
jQuery.type( function(){} ) === "function"
jQuery.type( [] ) === "array"
jQuery.type( new Date() ) === "date"
jQuery.type( new Error() ) === "error" // as of jQuery 1.9
jQuery.type( /test/ ) === "regexp"
其他一切都将返回它的类型“object”
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值