前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

为什么使用instanceof判断数组并不准确

qiguaw 2024-10-08 06:50:56 资源文章 16 ℃ 0 评论

如何判断变量是不是数组,这是前端的基础知识。这个问题也经常出现在面试中,有些同学会提出使用 instanceof 判断。但是这种方式在部分场景下是不准确的,今天就和大家一起分析一下。

instanceof 能够检测 构造函数的 prototype 属性是否在对象的原型链上。举个例子说明一下,方便理解。

instanceof 的判断过程是在检测对象的原型链上寻找构造函数的 prototype 属性。

第一个判断结果为 true 是因为 People.prototype 存在于 owen 的原型链上。
第二个判断结果为 false 是因为 String.prototype 不存在于 owen 的原型链上。

简单来说,instanceof 可以判断变量是否是由构造函数生成的。因为数组 Array 也是一个构造函数,所以可以用 instanceof 判断变量是不是数组。

Array.prototype 存在于 arr 的原型链上,其他两个变量的原型链上不存在。

但是这种方式真的能100%判断正确吗?我们再看一下 instanceof 判断的原理,检测构造函数的 prototype 属性是否在对象的原型链上。
如果修改了对象的原型链呢?

修改了 arr 的原型链之后,instanceof 判断就不准确了。

instanceof 在跨 iframe / window 时也会判断错误,因为使用的不是同一个构造函数。举个例子:

const iframeEl = document.createElement('iframe');
document.body.appendChild(iframeEl);
iframeArray = window.frames[window.frames.length - 1].Array;

const array1 = new Array(1,1,1,1);
const array2 = new iframeArray(1,1,1,1);

console.log(array1 instanceof Array);  // true    
console.log(array2 instanceof Array);  // false    


总结: 在绝大部分情况下使用 instanceof 能够准确地判断变量是否为数组,但是 instanceof 确实不是完美的办法。


欢迎大家评论转发~

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表