Today just learning to pay the Treasure JS framework base.js. With a glance, the realization is this:
Copy Code code as follows:
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 to say, chaos. Of course, it can be said that, "the most complete in history", it does use the most mainstream method, just write them all together.
As we know, using instanceof and constructor is the most direct and simple way:
Copy Code code as follows:
var arr = [];
Arr instanceof Array; True
Arr.constructor = = Array; True
Only, because the Array created in different IFRAME does not share prototype. If you use this. The trouble is coming. So, if you want to apply it to the framework, this approach is definitely not going to work. Instead, using Douglas Crockford's cramming method can solve this problem (the JavaScript language pristine P61):
Copy Code code as follows:
var Is_array = function (value) {
return value &&
typeof value = = = ' object ' &&
typeof value.length = = ' Number ' &&
typeof Value.splice = = ' function ' &&
! (value.propertyisenumerable (' length '));
};
But is there a simpler way? In fact, like our own use, is not it?
Copy Code code as follows:
Object.prototype.toString.call (value) = = ' [Object Array] '
The above notation is what jQuery is using. At present, Taobao's Kissy is also used in this way. Isn't that the simplest and most effective way to do so? Personal feeling the internal framework is a bit cumbersome to write. Routine summary, final plan:
Copy Code code as follows:
var IsArray = function (obj) {
return Object.prototype.toString.call (obj) = = ' [Object Array] ';
}
==============
update:2010.12.31 00:01 (source)
Judging type, it's cool. Specifically, with the above is a truth:
Copy Code code as follows:
The 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;
}