编写一个函数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/