js学习日记1
javascript中Array的类型为什么是object?
typeof可以检测基本类型包括 undefined,string, number, boolean,但是对于检测对象就不靠谱了。不只是Array,javascript中的对象,包括 Date, String, Boolean, Number, Object, Function, Array, RegExp, Error 使用typof只会返回 “object”。 使用 instanceof 或者 constructor 来检测 Array 也不是靠谱的办法。如果是待检测的数组来自一个iframe的数组时,instanceof和contructor都会失效。由于每个iframe都有一套自己的执行环境,跨frame实例化的对象彼此是不共享原型链的。
1
2
3
4
5
6
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]
arr instanceof Array; // false
arr.constructor === Array; // false
ECMA中对Object.prototype.toString的解释:
When the toString method is called, the following steps are taken:
- Get the http://Class property of this object.
- Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
- Return Result (2)
- 其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object、获取的类名、]组合并返回。
另外,ECMA中对Array有如下说明:The http://Class property of the newly constructed object is set to “Array”.其他对象类似。 因此使用这种方法既解决了instanceof存在的跨页面问题,也解决了属性检测方式所存在的问题。
另外,使用Object.prototype.toString,而不是Object.toString是因为toString可能被覆写。
1
2
3
4
5
6
7
8
9
10
11
var type=function(object){
return Object.prototype.toString.call(object);
}
type({}) //"[object Object]"
type([1,2,3,4]); //"[object Array]"
type(new Date()); //"[object Date]"
type(/^hello/); //"[object RegExp]"
type(new Error()) //"[object Error]"
type(new Number()) //"[object Number]"
//......
This post is licensed under CC BY 4.0 by the author.