Underscore.JS - map 方法



语法

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

map 方法通过映射元素列表上的每个值来生成新的值数组,同时迭代给定的元素列表,调用绑定到上下文对象的迭代器函数(如果已传递)。迭代器使用三个参数调用:(element, index, list)。对于 JavaScript 对象,迭代器的对象将是 (value, key, list)。返回列表以供链式处理。

示例

var _ = require('underscore');

//Example 1. get Square of each number of array
var list = _.map([1, 2, 3], function(x) { return x*x });
console.log(list);

//Example 2. get squre of each number of object
list = _.map({one: 1, two: 2, three: 3}, function(value, key) { return value*value });
console.log(list);

将以上程序保存到 tester.js 中。运行以下命令来执行此程序。

命令

\>node tester.js

输出

[ 1, 4, 9 ]
[ 1, 4, 9 ]
underscorejs_iterating_collection.htm
广告
© . All rights reserved.