I just happened to be learning the Alipay JS framework base.js today. After taking a look, the implementation is like this:
if (value instanceof Array ||
(!(value instanceof Object) &&
(Object.prototype.toString.call((value)) == '[object Array]') ||
typeof value.length = = 'number' &&
typeof value.splice != 'undefined' &&
typeof value.propertyIsEnumerable != 'undefined' &&
!value.propertyIsEnumerable('splice'))) {
return 'array';
}
How can I put it, it's chaotic. Of course, it can also be said to be "the most complete in history". It does use the most mainstream methods, but it just writes them all together.
As we know, using instanceof and constructor is the most direct and simple way:
var arr = [];
arr instanceof Array; // true
arr.constructor == Array; //true
But, because Arrays created in different iframes do not share prototype. If used like this. Trouble begins. So, if you want to apply it in a framework, this method will definitely not work. On the contrary, this problem can be solved by using Douglas Crockford's cramming method ("JavaScript Language Essence" P61):
var is_array = function(value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
However, are there any more What about the easy way? In fact, isn’t it just like what we use ourselves?
Object.prototype.toString.call(value) == '[object Array]'
The above writing method is what jQuery is using. Currently, Taobao’s kissy also uses this method. Isn't this the simplest and most effective way at present? Personally, I feel that the internal framework is a bit cumbersome to write. Routine summary, final solution:
var isArray = function( obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
==============
UPDATE: 2010.12.31 00:01 (Source)
Judge the type, cool. Specifically, it is the same as the above:
var is = function (obj,type) {
return (type === "Null" && obj === null) ||
(type === "Undefined" && obj === void 0 ) ||
(type === "Number" && isFinite(obj)) ||
Object.prototype.toString.call(obj).slice(8,-1) === type;
}