数组JavaScript问题.第一个元素转到最后一个位置



我有一个函数,它获取数组,并返回每个数组元素的幂为2的数组。这是源代码

const firstArr = [1, 2, 3, 7, 4, 9];
function arrayPow(arr) {
const outputArray = [];
arr.forEach(el => {
console.log(el);
outputArray.splice(-1, 0, el**2);
})
return outputArray;
}
console.log(arrayPow(firstArr));

我得到了这个作为输出:

script.js:8 1
script.js:8 2
script.js:8 3
script.js:8 7
script.js:8 4
script.js:8 9
script.js:14 (6) [4, 9, 49, 16, 81, 1]

循环中纠正错误的步骤。但现在,在数组中,有第一个元素,在某些原因中,停留在最后。我试图删除";1〃;从firstArr开始;4〃;转到最后一个位置。为什么

在拼接中放入-1意味着在数组的最后一个元素之前插入。当数组为空时,它只是作为唯一的项添加。

接下来,在数组的最后一个元素之前插入,因此每次后续迭代都会将该项添加为倒数第二个元素。

我只想使用ES6魔术:

const firstArr = [1, 2, 3, 7, 4, 9];
const arrayPow = (arr) => arr.map(i => i**2)
console.log(arrayPow(firstArr))

使用此代码,它将像魅力一样工作!

const firstArr = [1, 2, 3, 7, 4, 9];
function arrayPow(arr) {
return arr.map(v => v ** 2);
}
console.log(arrayPow(firstArr));

如果我正确理解你的问题,你想把数组中的每个元素都提高2的幂吗?如果是这样的话,我不确定你为什么要拼接这个阵列。您可以尝试以下操作:

function arrayPow(arr) {
const outputArray = [];
arr.forEach(el => {
outputArray.push(el**2);
})
return outputArray;
}
const test = [1,2,3]
console.log(arrayPow(test))

相关内容

最新更新