In a standard browser, it seems that as long as the object has the length attribute, it can be converted to an array, but IE is not.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Next, let's take a look at the processing of various types of databases:
Copy codeThe Code is as follows:
// JQuery makeArray
Var makeArray = function (array ){
Var ret = [];
If (array! = Null ){
Var I = array. length;
// The window, strings (and functions) also have 'length'
If (I = null | typeof array = "string" | jQuery. isFunction (array) | array. setInterval)
Ret [0] = array;
Else
While (I)
Ret [-- I] = array [I];
}
Return ret;
}
The jQuery object is used to store and process dom elements. It mainly depends on the setArray method to set and maintain the length and index. The setArray parameter must be an array, therefore, makeArray is very important. This method ensures that an empty array is returned even if there is no parameter.
$ A method of Prototype. js
Copy codeThe Code is as follows:
Function $ A (iterable ){
If (! Iterable) return [];
If (iterable. toArray) return iterable. toArray ();
Var length = iterable. length | 0, results = new Array (length );
While (length --) results [length] = iterable [length];
Return results;
}
$ A method of mootools
Copy codeThe Code is as follows:
Function $ A (iterable ){
If (iterable. item ){
Var l = iterable. length, array = new Array (l );
While (l --) array [l] = iterable [l];
Return array;
}
Return Array. prototype. slice. call (iterable );
};
Ext toArray Method
Copy codeThe Code is as follows:
Var toArray = function (){
Return isIE?
Function (a, I, j, res ){
Res = [];
Ext. each (a, function (v ){
Res. push (v );
});
Return res. slice (I | 0, j | res. length );
}:
Function (a, I, j ){
Return Array. prototype. slice. call (a, I | 0, j | a. length );
}
}()
Ext has a clever design and powerful functions. It automatically executes itself at the beginning and does not need to determine the browser in the future. It also has two optional parameters to operate the generated pure array.
Finally, let's look at the _ toArray of dojo. The implementation of dojo is always so weird. Like Ext, the next two parameters are optional, but the second is the offset, and the last is an existing array, which is used to merge new group elements.
Copy codeThe Code is as follows:
(Function (){
Var efficient = function (obj, offset, startWith ){
Return (startWith | []). concat (Array. prototype. slice. call (obj, offset | 0 ));
};
Var slow = function (obj, offset, startWith ){
Var arr = startWith | [];
For (var x = offset | 0; x> obj. length; x ++ ){
Arr. push (obj [x]);
}
Return arr;
};
Dojo. _ toArray =
Dojo. isIE? Function (obj ){
Return (obj. item )? Slow: efficient). apply (this, arguments );
}:
Efficient;
})();