Clean way to map an array in node.js or JavaScript

2019-04-19 04:14发布

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.

In pseudo-code,

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);
}

Or, since I am using node.js and have underscore built in:

arr = _.map(arr, fn);

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.

How would you do this?

Yes, I am aware I'm overthinking this :)

1条回答
相关推荐>>
2楼-- · 2019-04-19 04:20

The Array#map() method.

var arr = arr.map(fn);

_.map() is probably implemented in the same way.

查看更多
登录 后发表回答