- 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
廣告