Underscore Introduction:
Underscore is a very concise, practical JavaScript Library, similar to the jquery package type, but underscore is backbone's dependent library, and to run backbone you must first introduce underscore.js. "_" begins with a feature that relies on library underscore to distinguish between other library function names. "." is the name of the function after.
Underscore function:
The underscore encapsulates more than 60 functions for developers to use, followed by analysis.
1.each () and map functions
Each and map in underscore have a common feature, which is to iterate through each element of the set according to certain conditions. But the way they operate is different.
each () function:
The format of the call:
_.each (List,iterator,[context])
This function iterates through each element of the list, based on the filtering conditions provided by the iterator iterator.
Source:
vareach = _.each = _.foreach =function(obj, iterator, context) {if(obj = =NULL)return; if(Nativeforeach && Obj.foreach = = =Nativeforeach) { //if the hosting environment supports it, the Foreach method provided by JavaScript 1.6 is called firstObj.foreach (iterator, context); } Else if(Obj.length = = = +obj.length) {//executes the processor method on each element of the [array] for(vari = 0, length = obj.length; i < length; i++) { if(Iterator.call (context, obj[i], I, obj) = = = Breaker)return; } } Else { //executes the processor method on each element of the {object} varKeys =_.keys (obj); for(vari = 0, length = keys.length; i < length; i++) { if(Iterator.call (context, obj[keys[i]], keys[i], obj) = = = Breaker)return; } } };
Function idea: If the host supports the native foreach method, it is called directly to the native, if it is not supported to walk through the way, (generally, the browser or node. JS supports the native foreach method).
Here is a very rare way to judge, obj.length = = = +obj.length, known as the duck-type judgment of the way.
Underscore.js Dependent library function analysis A