js中的typeof 和 instanceof有哪些区别

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

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容