0
点赞
收藏
分享

微信扫一扫

js 判断数据类型的几种方法

AbrahamW 2022-04-08 阅读 108
javascript

演示数据:

let str = "str";
let num = 123;
let array = [1, 2, 3];
let date = new Date();
let func = function(){};
let symbol = Symbol();

一、typeof (常用)

用法

typeof str     // "string" 字符串
typeof num     // "number" 数值
typeof array   // "object" 对象(可以和函数区别开)
// 👆注意,数组也是一个对象
typeof date    // "object" 对象 
typeof func    // "function" 函数
typeof symbol  // "symbol"

还有一些看起来比较特殊的例子

// “null”被认为是一个对空白对象的引用
typeof null    // object

// 对于未声明的变量
typeof test    // undefined 未定义

// 对于声明过,但是未赋值的变量
let message;
typeof message // undefined 也是未定义,因为只声明但没有赋值

⚠️ 需要注意的是,typeof 返回的类型都是字符串形式:

typeof a == "string"  // true
typeof a == String  // false

二、instanceof

instanceof 用于判断一个引用值是不是给定引用类型(由原型链决定)的实例。语法如下:

//结果 = 对象 instanceof 构造函数
result = variable instanceof constructor

用法

array instanceof Array   // true
date instanceof Date     // true
func instanceof Function // true

原型链上的其他实例

事实上,除了判断自身,instanceof 还会沿着原型链往上找,只要 variable 的原型链上存在有 constructor 的实例,就可以说该 variable 属于该 constructor实例(继承),也就是返回结果true

所有引用值都是 Object 的实例(万物基于 Object

array instanceof Object  // true

沿着原型链查找

function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();
let sub = new SubType();

sub instanceof SubType    // true
sub instanceof SuperType  // true
sub instanceof Object     // true

一些特殊例子

// 如果用 instanceof 检测原始值,则始终返回 false
str instanceof String    // false

三、constructor

有时候我们只想判断当前对象是否为某构造函数的实例,而非连带原型链上的其他对象也一起判断。这种情况下,我们可以根据对象的 constructor 来进行判断:

function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();
// 把原型上的构造器指向自身,否则会判断错误
SubType.prototype.constructor = SubType;
let sub = new SubType();

sub.constructor === SubType    // true
sub.constructor === SuperType  // false
sub.constructor === Object     // false

四、prototype (通用但繁琐)

其实就是通过 toString 方法来把对象直接转换成字符串,和第一种方法相比,它能检测出基本引用类型,比如:DateRegExp 对象等。

Object.prototype.toString.call(str) === '[object String]'    // true
Object.prototype.toString.call(num) === '[object Number]'    // true
Object.prototype.toString.call(array) === '[object Array]'   // true
Object.prototype.toString.call(date) === '[object Date]'     // true
Object.prototype.toString.call(func) === '[object Function]' // true
Object.prototype.toString.call(symbol) === '[object Symbol]' // true
Object.prototype.toString.call(new Error()) === '[object Error]' //true

但是在自定义对象中调用时,只返回 [object Object]

以上。

举报

相关推荐

0 条评论