js 一网打尽之类型判断

let bool = true;
let num = 1;
let str = 'abc';
let  und= undefined;
let nul = null;
let arr = [1,2,3,4];
let obj = {name:'xiaoming',age:22};
let fun = function(){console.log('hello')};
let s1 = Symbol();

typeof

快速区分基本数据类型,但不能区分除funtion外的引用类型。

返回类型为string。
未定义的变量不会报错,返回 "undefiend"
typeof NaN → number


console.log(typeof bool); //boolean
console.log(typeof num);//number
console.log(typeof str);//string
console.log(typeof und);//undefined
console.log(typeof nul);//object
console.log(typeof arr);//object
console.log(typeof obj);//object
console.log(typeof fun);//function
console.log(typeof s1); //symbol

instanceof

obj instanceof constructor

检查constructor的prototype是否在obj的原型链上,只可以检测出引用类型,如array、object、function,同时对于是使用new声明的类型,它还可以检测出多层继承关系。

console.log(arr instanceof Array);// true
console.log(obj instanceof Object);// true
console.log(fun instanceof Function);// true

function Student(name){
  this.name=name
}
let s=new Student("小王")
console.log(s instanceof Student) //true

constructor

null、undefined没有construstor属性,因此constructor不能判断undefined和null。
但是他是不安全的,因为contructor的指向是可以被改变。

console.log(num.constructor === Number);// true

/* 可以被更改
num.__proto__.constructor=String;   
console.log(num.constructor === String) //true
*/

console.log(bool.constructor === Boolean);// true
console.log(str.constructor === String);// true
console.log(arr.constructor === Array);// true
console.log(obj.constructor === Object);// true
console.log(fun.constructor === Function);// true
console.log(s1.constructor === Symbol);//true

Object.prototype.toString.call

每个类型都继承了toString属性,对于Set,Map,object这些类型来说,它们的toString()和Object.prototype.toString()一样,而对基本类型和array这些类型(null和undefined没有toString方法),他们的toString()被改写成返回它们对应内容的字符串,所以对于这些类型来说,要使用Object.prototype.toString.call()来判断。

此方法可以相对较全的判断js的数据类型。

console.log(Object.prototype.toString.call(bool));//[object Boolean]
console.log(Object.prototype.toString.call(num));//[object Number]
console.log(Object.prototype.toString.call(str));//[object String]
console.log(Object.prototype.toString.call(und));//[object Undefined]
console.log(Object.prototype.toString.call(nul));//[object Null]
console.log(Object.prototype.toString.call(arr));//[object Array]
console.log(Object.prototype.toString.call(obj));//[object Object]
console.log(Object.prototype.toString.call(fun));//[object Function]
console.log(Object.prototype.toString.call(s1)); //[object Symbol]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值