5-8Underscore02
来源:互联网 发布:淘宝服装挂拍技巧 编辑:程序博客网 时间:2024/06/05 03:13
_.each
_.each(list, iteratee, [context]) 别名: forEach 遍历list中的所有元素,按顺序用遍历输出每个元素。如果传递了context参数,则把iteratee绑定到context对象上。每次调用iteratee都会传递三个参数:(element, index, list)。如果list是个JavaScript对象,iteratee的参数是 (value, key, list))。返回list以方便链式调用。(注:如果存在原生的forEach方法,Underscore就使用它代替。)
测试代码
_ = require('underscore'); var a = [1, 2, 3];function test(element, index, list) { if(list[index] == 2) { console.log(element); console.log(index); console.log(list); };};_.each(a,test(element, index, list));/* 输出21[ 1, 2, 3 ]第一行是数组中当前迭代到的值,第二行是该值的代码,第三行是这个数组*/
源码
_.each = _.forEach = function(obj, iteratee, context) { // 改变执行函数作用域 iteratee = optimizeCb(iteratee, context); var i, length; // 数组 if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { // 对象 var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj;};// 主要用来执行函数并改变所执行函数的作用域,argCount参数来指定参数个数,分类处理 var optimizeCb = function(func, context, argCount) { // void 0 表示underfined if (context === void 0) return func; switch (argCount) { // 接受单值的情况 case 1: return function(value) { return func.call(context, value); }; // The 2-parameter case has been omitted only because no current consumers // made use of it. case null: // 用于迭代器函数,比如foreach map pick case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; // 用于reduce reduceRight case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; };
_.iteratee
_.iteratee(value, [context]) 一个重要的内部函数用来生成可应用到集合中每个元素的回调, 返回想要的结果 - 无论是等式,任意回调,属性匹配,或属性访问。
测试代码
var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];_.map(stooges, _.iteratee('age'));=> [25, 21, 23];
源码
_.iteratee = builtinIteratee = function(value, context) { return cb(value, context, Infinity);};var cb = function(value, context, argCount) { if (_.iteratee !== builtinIteratee) return _.iteratee(value, context); if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value) && !_.isArray(value)) return _.matcher(value); return _.property(value);};
0 0
- 5-8Underscore02
- 8-5
- 5-8
- 8-5
- 5-8
- 5-8
- 8-5
- 8月5日
- 2006-5-8MusicPlayList
- 左手 右手(5-8)
- 2007-5-8加班
- 8月5日
- 8/5工作计划
- 2008-8-5
- 程序5-8 Clover
- 2009-5-8
- 8、示例5:TestPong
- 8元5角
- 多版本通讯录
- mybatis核心组件
- Quake4之GUI(2)
- java中string和int互相转化
- 图片自适应
- 5-8Underscore02
- 指针数组,数组指针,函数指针,函数指针数组,指向函数指针数组的指针
- java之继承中的构造方法
- Struts 2 中的<s:select>标签的使用和介绍
- #Android学习#Sqlite数据库的创建
- 关于RxSwift MVVM flatMapLatest 点击事件网络请求失败整个序列结束
- SpringMVC 几种控制器介绍
- Activity的详细解析
- java实现判断是手机端还是pc端访问