简体   繁体   中英

function like map() that doesn't create a new array

Is there a function like map() in JS that stores the returns in the original array, instead of making a new array? If not, what would be the most efficient way to do this?

Just use .forEach() instead:

myArray.forEach(function(value, index, array) {
    array[index] = ...   // some mutation of value
});

The exact same code would still work with .map (which invokes the callback with the same three parameters and therefore allows in-place mutation) but .forEach avoids the overhead of creating a new array, only to have it thrown away again immediately.

Note also that whilst one could just refer to myArray inside the callback, it's much more efficient not to. Having the array parameter passed to the callback allows the callback to manipulate or access the original array without requiring it to be in the lexical scope (although using this to insert or delete elements would be ill advised)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM