数据类型判断

数据类型判断

js数据类型判断有4种方式分别是:
typeof、instanceof、constructor、Object.prototype.toString.call()、jquery.type()

1:typeof

let str = ""
console.log(typeof str);

注意:尽量用来判断简单数据类型,除了null,null判断出来是object,判断object和array都会返回object
检测function返回回来的值为function

2. instanceof

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

instanceof检测基本数据类型都失败,返回值都为object,检测null和underfined会报错
只能检测引用数据类型

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

3.constructor
constructor是prototype对象上的属性,指向构造函数。根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。
根据对象的constructor判断,返回对创建此对象的数组函数的引用。

var c= [1,2,3]; 
var d = new Date(); 
var e = function(){alert(111);}; 
alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(e.constructor === Function) -------> true
//注意: constructor 在类继承时会出错

他在检测简单数据类型时,null和underfined的会报错,其他的可以

4.使用Object.prototype.toString.call()检测对象类型
一般情况下,js中对象的toString(),返回字符串,内容与函数声明语法有关,例如[1,2,3].toString()//“1,2,3”
大多数都返回函数的完整源码,Array.toString()//“function Array() { [native code] }”
内置函数往往返回一个类似"[native code]“的函数体,需要配合call方法,比如Object.prototype.toString.call([1,2,3])//”[object Array]"

function Dog(name) {
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
  return `${this.name}`;
};

console.log(dog1.toString());
// expected output: "Gabby"

5 .万能的方法: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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值