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对集合的支持。
- ~ vi collection.js
-
- //加载underscore库
- var _ = require("underscore")._;
each: 对集合循环操作
- _.each([1, 2, 3], function (ele, idx) {
- console.log(idx + ":" + ele);
- });
- => 0:1
- 1:2
- 2:3
map: 对集合以map方式遍历,产生一个新数组
- console.log(
- _.map([1, 2, 3], function(num){
- return num * 3;
- })
- );
- => [3, 6, 9]
reduce: 集合元素合并集的到memo
- console.log(
- _.reduce([1, 2, 3], function (memo, num) {
- return memo + num;
- }, 0)
- );
- => 6
filter: 过滤集合中符合条件的元素。注:find:只返回第一个
- console.log(
- _.filter([1, 2, 3, 4, 5, 6], function(num){
- return num % 2 == 0;
- })
- );
- => [ 2, 4, 6 ]
reject: 过滤集合中不符合条件的元素
- console.log(
- _.reject([1, 2, 3, 4, 5, 6], function(num){
- return num % 2 == 0;
- })
- );
- => [ 1, 3, 5 ]
where: 遍历list, 返回新的对象数组
- var list = [
- {title:"AAA",year: 1982},
- {title:"BBB",year: 1900},
- {title:"CCC",year: 1982}
- ];
- console.log(
- _.where(list,{year: 1982})
- );
- => [ { title: 'AAA', year: 1982 }, { title: 'CCC', year: 1982 } ]
contains:判断元素是否在list中
- console.log(
- _.contains([1, 2, 3], 3)
- );
invoke:通过函数名调用函数运行
- console.log(
- _.invoke([[5, 1, 7]], 'sort')
- );
- => [ [ 1, 5, 7 ] ]
pluck: 提取一个集合里指定的属性值
- var users = [
- {name: 'moe', age: 40},
- {name: 'larry', age: 50}
- ];
- console.log(
- _.pluck(users, 'name')
- );
- => [ 'moe', 'larry' ]
max,min,sortBy: 取list中的最大,最小元素,自定义比较器
- console.log(
- _.max(users, function (stooge) {
- return stooge.age;
- })
- );
- => { name: 'larry', age: 50 }
- var numbers = [10, 5, 100, 2, 1000];
- console.log(
- _.min(numbers)
- );
- => 2
- console.log(
- _.sortBy([3, 4, 2, 1 , 6], function (num) {
- return Math.max(num);
- })
- );
- => [ 1, 2, 3, 4, 6 ]
groupBy: 把一个集合分组成多个集合
- console.log(
- _.groupBy(['one', 'two', 'three'], 'length')
- );
- => { '3': [ 'one', 'two' ], '5': [ 'three' ] }
countBy: 把一个数据分组后计数
- onsole.log(
- _.countBy([1, 2, 3, 4, 5], function (num) {
- return num % 2 == 0 ? 'even' : 'odd';
- })
- );
- => { odd: 3, even: 2 }
shuffle: 随机打乱一个数据
- console.log(
- _.shuffle([1, 2, 3, 4, 5, 6])
- );
- => [ 1, 5, 2, 3, 6, 4 ]
toArray: 将list转换成一个数组
- console.log(
- (function () {
- return _.toArray(arguments).slice(1);
- })(1, 2, 3, 4)
- );
- => [ 2, 3, 4 ]
size: 得到list中元素个数
- console.log(
- _.size({one: 1, two: 2, three: 3})
- );
算法或大型HTML呈现而不阻碍UI更新线程很有用.
- _.defer(function(){ console.log('deferred'); });
- => deferred
throttle:返回一个类似于节流阀一样的函数, 当高频率的调用函数, 实际上会每隔 wait 毫秒才会调用一次. 对于高到您感觉不到的高频率执行的函数时非常有用.
- var throttled = _.throttle(function(){
- _(5).times(function(n){ console.log(n+":"+new Date()); });
- }, 100);
- throttled();
- => 0:Wed Aug 28 2013 14:20:48 GMT+0800
- 1:Wed Aug 28 2013 14:20:48 GMT+0800
- 2:Wed Aug 28 2013 14:20:48 GMT+0800
- 3:Wed Aug 28 2013 14:20:48 GMT+0800
- 4:Wed Aug 28 2013 14:20:48 GMT+0800
debounce: 返回函数的防反跳版本, 将延迟函数的执行(真正的执行)在函数最后一次调用时刻的等待xx毫秒之后,可以实现延迟加载。
- var lazyLoad = _.debounce(function(){
- console.log("lazy load 3s");
- }, 3000);
- lazyLoad();
- => lazy load 3s
once: 创建一个只能运行一次的函数. 重复调用此修改过的函数会没有效果, 只会返回第一次执行时返回的结果。单例模式。
- var initialize = _.once(function(){console.log('initialize');});
- initialize();
- initialize();
- => initialize
after: 对循环计数,只有超过计数,才会调用指定的函数
- var nums = [1,2,3,4];
- var renderNums = _.after(nums.length, function(){
- console.log('render nums');
- });
- _.each(nums, function(num) {
- console.log('each:'+num);
- renderNums();
- });
- => each:1
- each:2
- each:3
- each:4
- render nums
wrap: 以函数作为函数传递,可以增加函数调用前后的控制。有点类似于 “模板方法模式”
- var hello = function(name) { return "hello: " + name; };
- hello = _.wrap(hello, function(func) {
- return "before, " + func("moe") + ", after";
- });
- console.log(hello());
- => before, hello: moe, after
compose: 组合函数调用关系,把单独的f(),g(),h()组合成f(g(h()))
- var greet = function(name){ return "A: " + name; };
- var exclaim = function(statement){ return "B: "+statement + "!"; };
- var welcome = _.compose(exclaim, greet);
- console.log(welcome('moe'));
- => B: A: moe!
view plain copy
-
-
-
-
-
-
-
或者
[javascript] view plain copy
说明underscore.string.js可以独立于underscore.js存在,会暴露出s全局变量。
转自 http://blog.csdn.net/qhairen/article/details/49447787