我还是个新手.即使在阅读了多个答案和Mozilla.org文档后,我也有点困惑……我的问题是,如果有一个简单的数组,我可以很容易地使用.map、.Filter,但如果数组有对象,那么它就会变得有点混乱.

我必须在这里加上所有的年龄.

我知道.map可能不工作,因为它给出了一个新的数组(这里我不想要它),.Filter不工作(这是为了返回满足给定条件的元素),因为Each不返回任何东西.

我不允许使用for循环,但这在这里是最方便的(下面的代码是正确的,正在工作).

我还能怎么解决它呢?

const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
var total=0
//console.log(users.length)
for(let i=0;i<users.length;i++){
    //console.log(users[i].age)
   total+=users[i].age
}

console.log(total)

推荐答案

您可以在使用for的地方使用forEach

您可以使用MAP创建一个年龄数组,然后将其减go 以求和

您可以使用Filter仅计算年龄大于或等于50岁的人数

({age})正在使用解构来获得对象数组的年龄,作为total=users.map(item => { return item.age })的替代方案

const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];

// forEach needs the total initialised

let total=0
users.forEach(user => total+=user.age)
console.log(total)

// map plus reduce (to sum) does not need to initialise

total=users.map(({age}) => age)
.reduce((a,b) => a+b)
console.log(total)

// filter plus reduce also does not need initialising the total

let total50Plus=users.filter(({age}) => age>=50)
.reduce((a,b) => a.age+b.age)   // does not need an accumulator initialised
console.log(total50Plus)

// the standard reduce initialises the accumulator at the end of the function

total=users.reduce((acc,{age}) => acc+=age,0);  
console.log(total)

// full version 

total=users.reduce((accumulator, current) => {
  accumulator += current.age;
  return accumulator;
},0); // initialise the accumulator 
console.log(total)

Javascript相关问答推荐

调用SEARCH函数后,程序不会结束

Flisk和JS错误:未捕获的Syntax错误:意外的令牌'<'

从连接字符串创建客户端时,NodeJS连接到CosmosDB失败

JS生成具有给定数字和幻灯片计数的数组子集

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

如何在Angular中插入动态组件

MongoDB中的引用

在服务器上放置了Create Reaction App Build之后的空白页面

屏幕右侧屏障上的产卵点""

在JS中拖放:检测文件

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

material UI按钮组样式props 不反射

DOM不自动更新,尽管运行倒计时TS,JS

在不删除代码的情况下禁用Java弹出功能WordPress

使用插件构建包含chart.js提供程序的Angular 库?

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

Google脚本数组映射函数横向输出

为列表中的项目设置动画

FireBase FiRestore安全规则-嵌套对象的MapDiff

react 路由如何使用从加载器返回的数据