javascript - 使用reduce并跳过其中包含0的数组?
问题描述
[]
在空数组 ( )上使用 reduce 时出现 TypeError 。
我不想删除 0 或类似的东西,我宁愿减少只是将 0 返回到该数组。
这是我当前的代码:
function squareSum(numbers) {
let numList = numbers.map(x => Math.pow(x, 2));
const sum = numList.reduce((x, y) => {
return x + y
});
return sum;
}
错误:
TypeError: Reduce of an empty array with no initial value
解决方案
传递一个初始值作为reduce
方法的第二个参数。
如果您省略了初始值,即 the 的第二个参数,reduce
那么 reduce 假定您在第一次迭代时array[0]
是您的。y
reduce
function squareSum(numbers) {
let numList = numbers.map(x => Math.pow(x, 2));
const sum = numList.reduce((x, y) => {
return x + y
}, 0); // Change here. Use zero initially
return sum;
}
推荐阅读
- api - 使用 API Users.messages:删除
- react-native - 使用组件类反应抽屉式导航 v5x useNavigation()
- android - 我的 AdMob 测试设备 ID 已更改(Android)
- ios - How to Hide MPCommandCenter manually?
- amazon-web-services - AWS / Quicksight / AWS4Signer / Signature Mismatch
- php - How to batch update multiple records using CodeIgniter query builder?
- python - What is the best way to read a JSON file and obtain the values without the invisible characters in Python?
- selenium - Trying to perform selenium testing using chrome driver but facing issue with below error while executing in cli as headless browser
- python - 将值从表单传递到另一个页面
- sql - Recursive SQL Query with Postgres Ranges To Find Availability