在node.js或JavaScript中映射数组的干净方法 [英] Clean way to map an array in node.js or JavaScript
问题描述
假设我有一个函数和一个数组。我想通过将函数应用于数组中的每个条目来修改数组。该函数不直接修改该值;它返回一个新值。
Let's say I have a function and an array. I want to modify the array by applying the function to each entry in the array. The function does NOT modify the value directly; it returns a new value.
在伪代码中,
for (entry in array) {
entry = function(entry);
}
我有几种方法可以做到这一点:
There are a couple ways to do this that occurred to me:
for (var i = 0; i < arr.length; i++) {
arr[i] = fn(i);
}
或者,因为我使用的是node.js并且内置了下划线:
Or, since I am using node.js and have underscore built in:
arr = _.map(arr, fn);
但这看起来有点笨重。标准的for块感觉过于冗长,_. map函数重新分配整个数组,因此感觉效率低下。
But this both seem a little clunky. The standard "for" block feels overly verbose, and the _.map function re-assigns the entire array so feels inefficient.
你会怎么做?
是的,我知道我正在思考这个:)
Yes, I am aware I'm overthinking this :)
推荐答案
Array#map()方法。
var arr = arr.map(fn);
_。map()
可能已实施以同样的方式。
_.map()
is probably implemented in the same way.
这篇关于在node.js或JavaScript中映射数组的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!