javascript - map() 不保存新元素

标签 javascript arrays mapping

编写一个函数incrementByIndex,它接受将数字作为值的嵌套数组的数组,并返回一个数组,其中嵌套数组的每个元素都按该嵌套数组的索引递增。

确保使用正确的高阶函数

第一个嵌套数组的值增加了 0,因为它是第一个索引,第二个嵌套数组的值增加了 1,最后一个嵌套数组的值增加了 2

incrementByIndex([
  [1, 2, 3],
  [2, 7, 9],
  [10, 3, 44],
]); // => [[1, 2, 3], [3, 8, 10], [12, 5, 46]]

我的代码:

const incrementByIndex = function (array) { 
  
 array.forEach(function(el){
      el.map(function(elm){
        elm +el.indexOf(elm)
      })
      
    })
  return array;
  
};

输出是原始数组,这是为什么?

最佳答案

因为 map 不会改变原始数组,所以它会将内容输出到新数组。您必须将 el.map() 的结果分配给其他变量。另请注意,您在传递给 map 的函数中缺少 return 语句。

const incrementByIndex = function(array) {
  const newArray = [];
  array.forEach(function(el) {
    const mapResult = el.map(function(elm) {
      return elm + array.indexOf(el)
    })
    newArray.push(mapResult)

  })

  return newArray;

};

const result = incrementByIndex([
  [1, 2, 3],
  [2, 7, 9],
  [10, 3, 44],
]);

console.log(result); // [[1, 2, 3], [3, 8, 10], [12, 5, 46]]

关于javascript - map() 不保存新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63640973/

相关文章:

javascript - setTimeout 晚于 Promise

javascript - JavaScript 变量可以除法吗?

javascript - 路由器问题。当我在 react-router 版本 6 中更改任何路由器时,页面位置保持在最后一页位置

javascript - 如何使用 JavaScript 的 for 循环从对象中获取接下来的 3 个项目?

c++ - 获取数组中以 0 结尾的最大元素

Elasticsearch : Root mapping definition has unsupported parameter

JavaScript:删除其属性 === 值的对象

javascript - 如何按名称和列关联对象

c# - 如何将匿名类型转换为已知类型

Python计算器: Key Error