判断JavaScript数据类型的方式

东明兄 2018-10-08
0条评论 1,001 次浏览
东明兄 2018-10-080条评论 1,001 次浏览

typeof

typeof "ConardLi"  // string
typeof 123  // number
typeof true  // boolean
typeof Symbol()  // symbol
typeof undefined  // undefined
typeof function(){}  // function

使用type of 判断引用类型就不行了:


typeof [] // object typeof {} // object typeof new Date() // object typeof /^\d*$/; // object

instanceof

console.log(2 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
上方因为左侧不是对象  是基本数据类型 所以是false
[] instanceof Array // true
new Date() instanceof Date // true
new RegExp() instanceof RegExp // true

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

参数:object(要检测的对象.)constructor(某个构造函数)
描述:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

直接调用Object原型上未被覆盖的toString()方法

大部分引用类型比如Array、Date、RegExp等都重写了toString方法,所以需要直接调用Object的toString方法

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注