Underscore.JS - each 方法

语法

_.each(list, iteratee, [context]) 

每个方法都会遍历给定的元素列表,如果传递了,则调用绑定到上下文对象的 iteratee 函数。Iteratee 使用三个参数调用:(元素、索引、列表)。对于 JavaScript 对象,iteratee 的对象将是(值、键、列表)。返回列表以用于链接目的。

示例

var _ = require('underscore');

var list = '';

//示例 1. 访问数组中的每个数字
_.each([1, 2, 3], function(x) { list += x + ' ' });
console.log(list);

list = ''

//示例 2. 访问对象的每个键值
_.each({one: 1, two: 2, three: 3}, function(value, key) { list += key + ':' + value + ' ' });
console.log(list);

将上述程序保存在tester.js中。运行以下命令执行该程序。

命令

\>node tester.js

输出

1 2 3
one:1 two:2 three:3

underscorejs_iterating_collection.html