- Underscore.JS 教程
- Underscore.JS - 首页
- Underscore.JS - 概述
- Underscore.JS - 环境设置
- Underscore.JS - 迭代集合
- Underscore.JS - 处理集合
- Underscore.JS - 迭代数组
- Underscore.JS - 处理数组
- Underscore.JS - 函数
- Underscore.JS - 映射对象
- Underscore.JS - 更新对象
- Underscore.JS - 比较对象
- Underscore.JS - 实用程序
- Underscore.JS - 链式
- Underscore.JS 有用的资源
- Underscore.JS - 快速指南
- Underscore.JS - 有用的资源
- Underscore.JS - 讨论
Underscore.JS - reduce 方法
语法
_.reduce(list, iteratee, [memo], [context])
reduce 方法会将所有值减少为一个值。它迭代给定的元素列表,调用 iteratee 函数,该函数绑定到上下文对象(如果传递的话)。Iteratee 使用三个参数调用:(memo、元素、索引、列表)。对于 JavaScript 对象,iteratee 的对象将是 (memo、值、键、列表)。为此链接目的,它返回列表。
Memo 是归约的第一状态,reduce 的每个后续步骤都应该由此 iteratee 返回。如果在 reduce 的初始调用中没有传递 memo,则第一个元素将作为 memo 传递,同时在列表中对下一个元素调用 iteratee。
示例
var _ = require('underscore');
//Example 1. get sum of each number of array
var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num }, 0);
console.log(sum);
//Example 2. get sum of each number of object
sum = _.reduce({one: 1, two: 2, three: 3}, function(memo, num) { return memo + num }, 0);
console.log(sum);
将上述程序保存在 **tester.js** 中。运行以下命令来执行此程序。
命令
\>node tester.js
输出
6 6
underscorejs_iterating_collection.htm
广告