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

我只是一个虾纸丫 提交于 2019-12-06 18:06:40

问题


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:


The Array#map() method.

var arr = arr.map(fn);

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



来源:https://stackoverflow.com/questions/9729645/clean-way-to-map-an-array-in-node-js-or-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!