Grammar:
_.each (list, iteratee, [context])
Description
Perform some action on all elements of the collection in turn, returning the list as it is. Receives 3 parameters, the list collection can be understood as the data source; Iteratee is an iterator that can be understood as a callback method; context execution contexts.
- List can be arrays, objects, strings, and arguments
- Iteratee will pass the third parameter (element, index, list) or (value, key, list)
- Context can change the iteratee internal this
Example one: Each can loop arrays, objects, strings, and arguments
//iterating through an array_.each ([1, 2, 3],function(element, index, list) {Console.log (element);});//traversing Objects_.each ({one: ' A ', two: ' II ', three: ' Three '},function(value, key, list) {Console.log (value);});//Traversing Strings_.each (' 123 ',function(element, index, list) {Console.log (element);});//Traverse ArgumentsfunctionABC () {_.each (arguments,function(element, index, list) {Console.log (element); });} ABC (1, 2, 3);
Example two: Parameters passed by iteratee
//the case of an array_.each ([1, 2, 3],function(element, index, list) {Console.log (element, index, list); //1 0 [1, 2, 3] //2 1 [1, 2, 3] //3 2 [1, 2, 3]});//the case of the object_.each ({one: ' A ', two: ' II ', three: ' Three '},function(value, key, list) {Console.log (value, key, list); //one Object {one: "A", Two: "II", Three: "Three"} //two two Object {one: "I", "II", "three"): "Three"} //three three Object {one: "A", Two: "II", Three: "Three"}});
Example three: Context can change the internal iteratee this
function (element, index, list) { Console.log (this//window}); _.each ([ function (element, index, list) { Console.log (this//{key:1}}, { Key:1});
Example four: The return value of each
var function (element, index, list) {}); var function //[1, 2, 3]//Object {one: "A", Two: "II", Three: "Three"}
The _.foreach function is the same as the _.each.
_. ForEach ([1, 2, 3], function (element, index, list) { console. Log (element); });
Traversing a non-collection (traversing a special value will not be an error, but will not be executed.) When traversing a collection, it is best to make sure that he is an array or an object. )
_.each (NULL,function(element, index, list) {Console.log (element);//do not execute}); _.each (Undefined,function(element, index, list) {Console.log (element);//do not execute}); _.each (123,function(element, index, list) {Console.log (element);//do not execute}); _.each (NewDate (),function(element, index, list) {Console.log (element);//do not execute});
Iteratee can also be a global approach
// can play three times .
Underscorejs class Library _.each (list, iteratee, [context])