欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」js中的typeof 和 instanceof有哪些区别

作者 : 自学哈 本文共1024个字,预计阅读时间需要3分钟 2023-08-4 共62人阅读
也想出现在这里? 联系我们

typeof一般是用来判断简单数据类型的,对一个值使用 typeof 操作符会返回下列字符串之一:

“undefined”: 表示值未定义

“boolean”: 表示值为布尔值

“number”: 表示值为数值

“string”: 表示值为字符串

“object”:表示值为对象或null

“symbol”: 表示值为符号

“function”: 表示值为函数

const variable1 = undefined;
console.log(typeof variable1); // "undefined"

const variable2 = null;
console.log(typeof variable2); // "object": 因为特殊值 null 被认为是一个对空对象的引用

const variable3 = true;
console.log(typeof variable3); // "boolean"

const variable4 = 1;
console.log(typeof variable4); // "number"

const variable5 = "hello";
console.log(typeof variable5); // "string"

const variable6 = Symbol();
console.log(typeof variable6); // "symbol"

function fn() {};
console.log(typeof fn); // "function"

instanceof
typeof ([]); // "object"
typeof ({}); // "object"
typeof (new String("1")); // "object"

从上面的例子可以看到,typeof的弊端就是会把复杂数据类型都解释为”object”,所以对复杂数据类型的判断就不能用typeof。

 

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,主要是用来判断复杂数据类型,返回布尔值,表示是否是某种类型(用于判断一个变量是否属于某个对象的实例:

// 使用语法: 
object instanceof constructo

// 具体例子如下:
const arr = [];
arr instanceof Array; // true

const obj = {};
obj instanceof Object; // true

const str = new String("1");
str instanceof String; // true

 

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」js中的typeof 和 instanceof有哪些区别
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号