简体   繁体   English

像map()这样的函数不会创建新数组

[英]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.

相关问题 数组映射函数不改变元素 - Array map function doesn't change elements 是否有像 function 这样的 .map 对象? 使用相同的密钥创建一个新的 object - Is there a `.map` like function for objects? To create a new object with the same keys 如何使用类似函数的映射创建数组的浅表副本? - How can I create a shallow copy of an array with a map like function? map函数不返回数组单词的长度 - map function doesn't return length of array's words `document.getElementsByClassName`的结果没有定义像`map`这样的数组方法,即使它是一个数组 - Result of `document.getElementsByClassName` doesn't have array methods like `map` defined, even though it is an array Map function 在 React 中没有 map 任务 - Map function doesn't map tasks in React 为什么在Angular的ngFor表达式中不能使用诸如filter和map这样的数组函数? - Why array functions like 'filter' and 'map' doesn't work in 'ngFor' expression of Angular? Map 一个数组创建一个新数组对 - Map an array to create a new array of pairs Map 数组 object 创建新数组 - Map array of object to create new array 为什么我不能使用_.map创建一个随机数组(new Array(n),Math.random)? - Why can't I create a random array using _.map(new Array(n), Math.random)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM