underscore.js学习笔记


一、理清概念

JavaScript对象原型中进行扩展,而是像jQuery一样,将数据封装在一个自定义对象中(下文中称“Underscore对象”)。可以通过调用一个Underscore对象的value()方法来获取原生的javascript数据。

3、Underscore.js是一个很精干的库,压缩后只有4KB。它提供了几十种函数式编程的方法,弥补了标准库的不足,大大方便了JavaScript的编程。MVC框架Backbone.js就将这个库作为自己的工具库。除了可以在浏览器环境使用,Underscore.js还可以用于Node.js。Underscor.js定义了一个下划线(_)对象,函数库的所有方法都属于这个对象。这些方法大致上可以分成:集合(collection)、数组(array)、函数(function)、对象(object)和工具(utility)五大类。

二、常用库函数

测试underscore对集合的支持。

  1. ~ vi collection.js
  2.  
  3. //加载underscore库
  4. var _ = require("underscore")._;

each: 对集合循环操作

  1. _.each([1, 2, 3], function (ele, idx) {
  2. console.log(idx + ":" + ele);
  3. });
  4. => 0:1
  5. 1:2
  6. 2:3

map: 对集合以map方式遍历,产生一个新数组

  1. console.log(
  2. _.map([1, 2, 3], function(num){
  3. return num * 3;
  4. })
  5. );
  6. => [3, 6, 9]

reduce: 集合元素合并集的到memo

  1. console.log(
  2. _.reduce([1, 2, 3], function (memo, num) {
  3. return memo + num;
  4. }, 0)
  5. );
  6. => 6

filter: 过滤集合中符合条件的元素。注:find:只返回第一个

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

reject: 过滤集合中不符合条件的元素

  1. console.log(
  2. _.reject([1, 2, 3, 4, 5, 6], function(num){
  3. return num % 2 == 0;
  4. })
  5. );
  6. => [ 1, 3, 5 ]

where: 遍历list, 返回新的对象数组

  1. var list = [
  2. {title:"AAA",year: 1982},
  3. {title:"BBB",year: 1900},
  4. {title:"CCC",year: 1982}
  5. ];
  6. console.log(
  7. _.where(list,{year: 1982})
  8. );
  9. => [ { title: 'AAA', year: 1982 }, { title: 'CCC', year: 1982 } ]

contains:判断元素是否在list中

  1. console.log(
  2. _.contains([1, 2, 3], 3)
  3. );

invoke:通过函数名调用函数运行

  1. console.log(
  2. _.invoke([[5, 1, 7]], 'sort')
  3. );
  4. => [ [ 1, 5, 7 ] ]

pluck: 提取一个集合里指定的属性值

  1. var users = [
  2. {name: 'moe', age: 40},
  3. {name: 'larry', age: 50}
  4. ];
  5. console.log(
  6. _.pluck(users, 'name')
  7. );
  8. => [ 'moe', 'larry' ]

max,min,sortBy: 取list中的最大,最小元素,自定义比较器

  1. console.log(
  2. _.max(users, function (stooge) {
  3. return stooge.age;
  4. })
  5. );
  6. => { name: 'larry', age: 50 }
  7.  
  8. var numbers = [10, 5, 100, 2, 1000];
  9. console.log(
  10. _.min(numbers)
  11. );
  12. => 2
  13.  
  14. console.log(
  15. _.sortBy([3, 4, 2, 1 , 6], function (num) {
  16. return Math.max(num);
  17. })
  18. );
  19. => [ 1, 2, 3, 4, 6 ]

groupBy: 把一个集合分组成多个集合

  1. console.log(
  2. _.groupBy(['one', 'two', 'three'], 'length')
  3. );
  4. => { '3': [ 'one', 'two' ], '5': [ 'three' ] }

countBy: 把一个数据分组后计数

  1. onsole.log(
  2. _.countBy([1, 2, 3, 4, 5], function (num) {
  3. return num % 2 == 0 ? 'even' : 'odd';
  4. })
  5. );
  6. => { odd: 3, even: 2 }

shuffle: 随机打乱一个数据

  1. console.log(
  2. _.shuffle([1, 2, 3, 4, 5, 6])
  3. );
  4. => [ 1, 5, 2, 3, 6, 4 ]

toArray: 将list转换成一个数组

  1. console.log(
  2. (function () {
  3. return _.toArray(arguments).slice(1);
  4. })(1, 2, 3, 4)
  5. );
  6. => [ 2, 3, 4 ]

size: 得到list中元素个数

  1. console.log(
  2. _.size({one: 1, two: 2, three: 3})
  3. );

算法或大型HTML呈现而不阻碍UI更新线程很有用.

  1. _.defer(function(){ console.log('deferred'); });
  2. => deferred

throttle:返回一个类似于节流阀一样的函数, 当高频率的调用函数, 实际上会每隔 wait 毫秒才会调用一次. 对于高到您感觉不到的高频率执行的函数时非常有用.

  1. var throttled = _.throttle(function(){
  2. _(5).times(function(n){ console.log(n+":"+new Date()); });
  3. }, 100);
  4. throttled();
  5. => 0:Wed Aug 28 2013 14:20:48 GMT+0800
  6. 1:Wed Aug 28 2013 14:20:48 GMT+0800
  7. 2:Wed Aug 28 2013 14:20:48 GMT+0800
  8. 3:Wed Aug 28 2013 14:20:48 GMT+0800
  9. 4:Wed Aug 28 2013 14:20:48 GMT+0800

debounce: 返回函数的防反跳版本, 将延迟函数的执行(真正的执行)在函数最后一次调用时刻的等待xx毫秒之后,可以实现延迟加载。

  1. var lazyLoad = _.debounce(function(){
  2. console.log("lazy load 3s");
  3. }, 3000);
  4. lazyLoad();
  5. => lazy load 3s

once: 创建一个只能运行一次的函数. 重复调用此修改过的函数会没有效果, 只会返回第一次执行时返回的结果。单例模式。

  1. var initialize = _.once(function(){console.log('initialize');});
  2. initialize();
  3. initialize();
  4. => initialize

after: 对循环计数,只有超过计数,才会调用指定的函数

  1. var nums = [1,2,3,4];
  2. var renderNums = _.after(nums.length, function(){
  3. console.log('render nums');
  4. });
  5. _.each(nums, function(num) {
  6. console.log('each:'+num);
  7. renderNums();
  8. });
  9. => each:1
  10. each:2
  11. each:3
  12. each:4
  13. render nums

wrap: 以函数作为函数传递,可以增加函数调用前后的控制。有点类似于 “模板方法模式”

  1. var hello = function(name) { return "hello: " + name; };
  2. hello = _.wrap(hello, function(func) {
  3. return "before, " + func("moe") + ", after";
  4. });
  5. console.log(hello());
  6. => before, hello: moe, after

compose: 组合函数调用关系,把单独的f(),g(),h()组合成f(g(h()))

  1. var greet = function(name){ return "A: " + name; };
  2. var exclaim = function(statement){ return "B: "+statement + "!"; };
  3. var welcome = _.compose(exclaim, greet);
  4. console.log(welcome('moe'));
  5. => B: A: moe!

view plain copy  
  1. "underscore.js">  
  2. "underscore.string.js">  
  3.   
  4.   
  5.   
  6.   
  7. "text/javascript">    
  8.         console.log(s.exports());  
  9.         _.mixin(s.exports());  
  10.         alert(_.capitalize("sdfds"));  
  11.       
  12.   

或者

[javascript] view plain copy  
  1. "underscore.string.js">  
  2.   
  3.   
  4. "text/javascript">    
  5.       
  6.     console.log(s.capitalize("fuckit"));  
  7.   
  8.       
  9.   


说明underscore.string.js可以独立于underscore.js存在,会暴露出s全局变量。

转自 http://blog.csdn.net/qhairen/article/details/49447787