Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

有以下 3 个判断数组的方法,请分别介绍它们之间的区别和优劣Object.prototype.toString.call() 、 instanceof 以及 Array.isArray() #4

Open
lovelmh13 opened this issue Jan 29, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

Object.prototype.toString.call

Object.prototype.toString.call 可以准确的判断出每个变量的类型,包括Array、Object、null、undefined

call用来改变toString的执行上下文

这个方法不能校验自定义类型:

function Animal (){}
let a = new Animal()
Object.prototype.toString.call(a) // "[object Object]"

instanceof

instanceof 只能判断出复杂类型的类型。是因为instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

var a = [];
a instanceof Array // true 

function B() {};
var b = new B()
a.__proto__ = b;

a instanceof Array // false
a instanceof B // true

并且:判断是不是Object,只要是复杂类型 都是true

a instanceof Object // true

另:instanceof不能检测来自iframe的数组

Array.isArray

只能用于判断是否是数组。

Array.isArray 可以检测来自iframe的数组

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
Object.prototype.toString.call(arr); // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false

性能:

Array.isArray 的性能最好,instanceof 比 toString.call 稍微好了一点点。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant