如何判断变量类型

在JS中如何判断变量的类型属于基础知识,很多时候我们会忽略。毕竟上手代码的时候可以现查。无论如何演变,我想基本功还是很重要的,熟练掌握总是百利而无一害。

1、首先第一种就是我们常用的typeof(),它会将类型信息当作字符串返回。如下:

console.log(typeof undefined); //undefined
console.log(typeof 5); //number
console.log(typeof true); //boolean
console.log(typeof 'hello world!'); //string复制代码

很完美对不对?但我们知道,这个世界几乎没有什么是完美的。看看下面的栗子就知道了:

console.log(typeof ['h', 'e', 'l', 'l', 'o']); //object
console.log(typeof { name: 'susu', age: 3 }); //object
console.log(typeof null); //object
console.log(typeof new Date()); //object复制代码

打印出来的结果都是object类型。通过上面的打印结果,我们知道typeof在判断变量类型的时候比较适合用来处理基本数据类型,如果是引用类型的值,typeof恐怕就心有余而力不足了。

2、instanceof:该运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。

let arr = [1, 2, 3];
let obj = { name: 'susu', age: 3 };
console.log(obj instanceof Array); //false
console.log(obj instanceof Object); //true复制代码

通过instanceof很容易就能判断一个变量是数组还是对象,貌似比typeof要高级了一些。但如果遇到数组,情况可能跟我们想象的不一样了。

let arr = [1, 2, 3];
console.log(arr instanceof Array); //true
console.log(arr instanceof Object); //true复制代码

为什么都是true呢?看看上面instanceof运算符的定义,是用来测试一个对象在原型链上是否存在一个构造函数的prototype属性。只要熟悉原型链就会知道,每个对象都有一个__proto__属性,指向创建该对象的函数的prototype。instanceof的判断规则是通过__proto__和prototype能否找到同一个引用对象。通过打印下面的等式,我们就能知道为什么上面的栗子都会打印出true。

console.log(arr.__proto__.__proto__ === Object.prototype); //true
console.log(arr.__proto__ === Array.prototype); //true复制代码

3、constructor:此属性返回对创建此对象的数组函数的引用

let arr = [1, 2, 3];
let obj = { name: 'susu', age: 3 };
console.log(arr.constructor === Array); //true
console.log(arr.constructor === Object); //false
console.log(obj.constructor === Array); //false
console.log(obj.constructor === Object); //true
复制代码

4、Object.prototype.toString.call():在js中该方法可以精准的判断对象类型,也是推荐使用的方法。

可以判断基本数据类型:

console.log(Object.prototype.toString.call(3)); //[object Number]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call('hello')); //[object String]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]复制代码

也可以判断引用数据类型:

let arr = [1, 2, 3];
let obj = {name: 'susu', age: 3};
let date = new Date();
function fn(){console.log('hello world!')}; 
       
console.log(Object.prototype.toString.call(arr)); //[object Array]    
console.log(Object.prototype.toString.call(obj)); //[object Object]      
console.log(Object.prototype.toString.call(date)); //[object Date]      
console.log(Object.prototype.toString.call(fn)); //[object Function]复制代码

以上。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值