underscorejs类库之_.each(list, iteratee, [context])
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了underscorejs类库之_.each(list, iteratee, [context])相关的知识,希望对你有一定的参考价值。
语法:
_.each(list, iteratee, [context])
说明:
依次对集合的所有元素进行某种操作,原样返回list。接收3个参数,list集合可以理解为数据源;iteratee即迭代器可以理解为回调方法;context执行上下文。
- list可以为数组,对象,字符串和arguments
- iteratee 会传第三个参数(element, index, list)或(value, key, list)
- context可以改变iteratee内部的this
示例一:each可以循环数组、对象、字符串和arguments
//遍历数组 _.each([1, 2, 3], function (element, index, list) { console.log(element); }); //遍历对象 _.each({one: ‘一‘, two: ‘二‘, three: ‘三‘}, function(value, key, list){ console.log(value); }); //遍历字符串 _.each(‘123‘, function(element, index, list){ console.log(element); }); //遍历arguments function abc(){ _.each(arguments, function(element, index, list){ console.log(element); }); } abc(1, 2, 3);
示例二:iteratee传递的参数
//数组的情况 _.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] }); //对象的情况 _.each({one: ‘一‘, two: ‘二‘, three: ‘三‘}, function(value, key, list){ console.log(value, key, list); //一 one Object {one: "一", two: "二", three: "三"} //二 two Object {one: "一", two: "二", three: "三"} //三 three Object {one: "一", two: "二", three: "三"} });
示例三:context可以改变iteratee内部的this
_.each([1], function (element, index, list) { console.log(this); //window }); _.each([1], function (element, index, list) { console.log(this); //{key: 1} }, {key : 1});
示例四:each的返回值
var arr1 = _.each([1, 2, 3], function (element, index, list) { }); var arr2 = _.each({one: ‘一‘, two: ‘二‘, three: ‘三‘}, function(element, index, list){ }); console.log(arr1); //[1, 2, 3] console.log(arr2); //Object {one: "一", two: "二", three: "三"}
_.forEach的功能和_.each是一样的
_.forEach([1, 2, 3], function (element, index, list) { console.log(element); });
遍历非集合(遍历特殊值都不会报错,但也不执行。在遍历一个集合的时候,最好能先确定他是数组或对象等。)
_.each(null, function (element, index, list) { console.log(element); //不执行 }); _.each(undefined, function (element, index, list) { console.log(element); //不执行 }); _.each(123, function (element, index, list) { console.log(element); //不执行 }); _.each(new Date(), function (element, index, list) { console.log(element); //不执行 });
iteratee还可以是全局的方法
_.each([1, 2, 3], alert); //会弹三次
以上是关于underscorejs类库之_.each(list, iteratee, [context])的主要内容,如果未能解决你的问题,请参考以下文章