我有獲取陣列的函式,并回傳每個陣列元素的冪為 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]
回圈中正確的元素程式。但是現在在陣列中,第一個元素,在某種意義上,留在了最后。我試圖從 firstArr 中洗掉“1”,然后將“4”移到最后一個位置。 為什么?
uj5u.com熱心網友回復:
將 -1 放在拼接中意味著您在陣列中的最后一個元素之前插入。當陣列為空時,它只是作為唯一項添加。
接下來,您然后在陣列的最后一個元素之前插入,因此每次后續迭代都會將該專案添加為倒數第二個元素。
我只會使用 ES6 魔法:
const firstArr = [1, 2, 3, 7, 4, 9];
const arrayPow = (arr) => arr.map(i => i**2)
console.log(arrayPow(firstArr))
uj5u.com熱心網友回復:
使用此代碼,它會像魅力一樣作業!
const firstArr = [1, 2, 3, 7, 4, 9];
function arrayPow(arr) {
return arr.map(v => v ** 2);
}
console.log(arrayPow(firstArr));
uj5u.com熱心網友回復:
如果我正確理解您的問題,您想通過 2 的冪提高陣列中的每個元素嗎?如果是這樣,我不確定您為什么要拼接陣列。您可以嘗試以下操作:
function arrayPow(arr) {
const outputArray = [];
arr.forEach(el => {
outputArray.push(el**2);
})
return outputArray;
}
const test = [1,2,3]
console.log(arrayPow(test))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364811.html
標籤:javascript 数组
