昨晚无意间接触到underscore.js,这是一个包括了很多基本功能函数的js库,里面有很多实用、你会非常需要的函数。而且它没有扩展javascript的原生对象。主要涉及对Collection、Object、Array、Function的操作。废话不多说,在后面我会一个一个函数的拿出来讲,大概60多个函数。 其实我甚至没有用过几个函数,也是从零开始慢慢看,然后记录学习过程。我是从官网学习然后写下来,基本上就是翻译。英文水平有限,如有疑义,欢迎拍砖。 Collection Functions (Arrays or Objects) 【集合函数】#each# 迭代list中的所有元素,按顺序用迭代器输出每个元素。如果传递了context参数,则把iterator绑定到context对象上。每次调用iterator都会传递三个参数: _.each([1, 2, 3], function(num){ console.log(num); }); // 1,2,3 _.each({one : 1, two : 2, three : 3}, function(num, key){ console.log(num); }); // 1,2,3 // html: var p = document.getElementsByTagName(‘p’); _.each(p , function( value, key, list ){ console.log( value ); // p1,p2,p2 console.log( key ); // 0,1,2 }) #map# 用转换函数把list中的每个值映射到一个新的数组。如果list是个JavaScript对象,iterator的参数是 var r = _.map([1, 2, 3], function(num){ return num * 3; }); console.log(r); // [3, 6, 9] var r = _.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; }); console.log(r); // [3, 6, 9] #reduce# reduce方法把列表中元素归结为一个简单的数值,。Memo是reduce函数的初始值,reduce的每一步都需要由iterator返回。 var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); // 6 这个函数有些浏览器提供了原生的,但是对不知道的童鞋,可能很难通过这个例子明白函数的试用方法,好的,看源码: // 代码的前面就声明了一个变量,检测是否支持原生reduce: var nativeReduce = ArrayProto.reduce; _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { // 使用原生的reduce if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError('Reduce of empty array with no initial value'); return memo; }; 解释上面的例子就是:试用迭代器把obj(1,2,3)里面的元素相加,由于设置了初始值(0),那就先加初始值,每次的相加的值都存储在memo里面。所以结果是0+1+2+3=6。 #reduceRight# reducRight是从右侧开始组合的元素的reduce函数,如果存在JavaScript 1.8版本的reduceRight,则用其代替。Foldr在javascript中不像其它有懒计算的语言那么有用(lazy evaluation:一种求值策略,只有当表达式的值真正需要时才对表达式进行计算)。 var list = [[0, 1], [2, 3], [4, 5]]; var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); => [4, 5, 2, 3, 0, 1] 好了,今天就先到这里。 |
|
来自: 飞鹰飞龙飞天 > 《underscore》