[英]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? 在JS中是否存在类似map()的函数,它将返回值存储在原始数组中,而不是创建新数组? If not, what would be the most efficient way to do this?
如果没有,那么最有效的方法是什么?
Just use .forEach()
instead: 只需使用
.forEach()
代替:
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. 完全相同的代码仍然可以使用
.map
(它使用相同的三个参数调用回调,因此允许就地突变),但.forEach
避免了创建新数组的开销,只是让它立即被丢弃。
Note also that whilst one could just refer to myArray
inside the callback, it's much more efficient not to. 还要注意,虽然人们可以在回调中引用
myArray
,但是它的效率要高得多。 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) 将
array
参数传递给回调允许回调操作或访问原始数组,而不要求它在词法范围内(尽管使用它来插入或删除元素将是不明智的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.