`
jinhonglin001
  • 浏览: 14581 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

js-underscore的学习

 
阅读更多

     在学习过程中是需要用到underscore.js的,所以需要从头开始认识,了解,掌握underscore.js的用法。

underscore里有许多函数,主要涉及collection、object、array、function的一些操作。

    下面是关于collection的一些函数。从官网总结一下最近用到的函数。

each

    语法

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

    描述:

    遍历list中的所有元素,按顺序用遍历输出每个元素。如果传递了context参数,则把iteratee绑定到 context对象上。每次调用iteratee都会传递三个参数:(element, index, list)。如果list是个JavaScript对象,iteratee的参数是(value, key, list))。返回list以方便链式调用。

例:

_.each([1, 2, 3], function(num){console.log(num)});
_.each({one: 1, two: 2, three: 3}, function(value,key){console.log(key)
console.log(value)});

输出:

1
2
3
one: 1, two: 2, three: 3 

 map

    语法:

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

     描述:
     通过转换函数(iteratee迭代器)映射列表中的每个值产生价值的新数组。iteratee传递三个参数:value,然后是迭代 index(或 key 愚人码头注:如果list是个JavaScript对象是,这个参数就是key),最后一个是引用指向整个list map  each的区别就是map可以接受返回值 

例:

_.map([1, 2, 3], function(num){ return num +1; });
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num +3; });
_.map([[1, 2], [3, 4]], _.first);
_.map([1,2,3],function(num){if(num > 2){return num }});
 输出:
[2, 3, 4]
[4, 5, 6]
[1, 3]
[undefined,2,3]

 我想通过第四个例子也可以稍微看出map和each的一点区别了,map是对list的值操作返回相同长度的数组,each是对list元素进行迭代,可以改变list的长度,没有返回值。

filter

    语法:

_.filter(list, predicate, [context]) 

     描述:
遍历list中的每个值,返回包含所有通过predicate真值检测的元素值。(愚人码头注:如果存在原生filter方法,则用原生的filter方法。)

例:

var arr = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

 输出:

[2, 4, 6] 

 fiiter也是当迭代list之后只会返回出符合条件的元素,list的长度并不会发生改变。

 

这就是最近常用到的一些迭代的函数。要分清操作的对象是什么。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics