underscorejs-each学习

2.1 each

2.1.1 语法:

_.each(list, iteratee, [context])

2.1.2 说明:

依次对集合的所有元素进行某种操作,原样返回list。接收3个参数,list集合可以理解为数据源;iteratee即迭代器可以理解为回调方法;context执行上下文。

  • list可以为数组,对象,字符串和arguments
  • iteratee 会传第三个参数(element, index, list)或(value, key, list)
  • context可以改变iteratee内部的this

2.1.3 代码示例:

示例一: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: "三"}

2.1.4 _.forEach的功能和_.each是一样的

_.forEach([1, 2, 3], function (element, index, list) {
    console.log(element);
});

2.1.5 遍历非集合

_.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); //不执行
});

遍历特殊值都不会报错,但也不执行。在遍历一个集合的时候,最好能先确定他是数组或对象等。

2.1.6 iteratee还可以是全局的方法

_.each([1, 2, 3], alert); //会弹三次

2.1.7 iteratee里面console.log为什么不行?(坑)

_.each([1, 2, 3], console.log); //Uncaught TypeError: Illegal invocation

gitbook地址:https://www.gitbook.com/book/niec-fe/underscorejs/details

你可能感兴趣的:(underscorejs-each学习)