You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
variframe=document.createElement('iframe');document.body.appendChild(iframe);xArray=window.frames[window.frames.length-1].Array;vararr=newxArray(1,2,3);// [1,2,3]// Correctly checking for ArrayArray.isArray(arr);// trueObject.prototype.toString.call(arr);// true// Considered harmful, because doesn't work though iframesarrinstanceofArray;// false
Object.prototype.toString.call
Object.prototype.toString.call 可以准确的判断出每个变量的类型,包括Array、Object、null、undefined
call用来改变
toString
的执行上下文这个方法不能校验自定义类型:
instanceof
instanceof 只能判断出复杂类型的类型。是因为
instanceof
运算符用来检测constructor.prototype
是否存在于参数object
的原型链上。并且:判断是不是Object,只要是复杂类型 都是true
另:instanceof不能检测来自iframe的数组
Array.isArray
只能用于判断是否是数组。
Array.isArray 可以检测来自iframe的数组
性能:
Array.isArray 的性能最好,instanceof 比 toString.call 稍微好了一点点。
The text was updated successfully, but these errors were encountered: