如标题所述,我试图获取一个数字数组,然后返回该数组平方中所有偶数数字的和。
我可以让我的函数返回给定数组中所有偶数之和,但是无法使它对偶数之和求平方。
这是我到目前为止的内容:
let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squareEvenNumbers = (numStr) => {
let sum = 0;
for (let i = 0; i < numStr.length; i++) {
if (numStr[i] % 2 === 0) {
sum = Math.pow(sum + numStr[i], 2);
}
}
return sum
}
console.log(squareEvenNumbers(numStr));
最佳答案
您只需要将数组中的当前项目提高到2的幂,而不是整个sum
:
let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squareEvenNumbers = (numStr) => {
let sum = 0;
for (let i = 0; i < numStr.length; i++) {
if (numStr[i] % 2 === 0) {
sum += Math.pow(numStr[i], 2);
}
}
return sum
}
console.log(squareEvenNumbers(numStr));
或者,更简洁地说:
let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squareEvenNumbers = arr => arr
.filter(num => num % 2 === 0)
.reduce((a, num) => a + num ** 2, 0);
console.log(squareEvenNumbers(numStr));
或者,仅对数组进行一次迭代:
let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squareEvenNumbers = arr => arr
.reduce((a, num) => a + (num % 2 === 0 && num ** 2), 0);
console.log(squareEvenNumbers(numStr));