JavaScript 函数 - 计算某个值在对象数组中的出现次数

我接到了一项任务,我一定是遗漏了什么。提供的代码不是原始问题,而是相似的。我必须计算阵列中有多少人年龄在 16 岁或以上。我玩过它,但我无法解决。请,有人可以解释我做错了什么吗?


在任务中,我得到了一组对象:


var people = [{name:'Emma', age:15},{name:'Matt', age: 16}, {name:'Janet', age:17}]

我需要完成一个函数来计算有多少人年满 16 岁。给出了函数的开始(即function correctAge(people){ //Complete })


“示例代码”是我一直在玩的一些骨架代码。“不正确的尝试”是我的尝试,它是我不断返回的代码,或者它的变体也是正确的......


请帮忙


错误的尝试:


var people = [

  {name: "Emma", age: 15},

  {name: "Matt", age: 16},

  {name: "Tom", age: 17}

];


function correctAge(array) {

  // Complete the function to return how many people are age 16+

  var count = 0;


  for (let i = 0; i < array.length; i++) {

    var obj = array.length[i];

    for (prop in obj) {

      if (prop[obj] >= 16) {

        count++;

      }

    }

    return count;

  }

}


console.log(correctAge(people));

示例代码:


var people = [

  {name: "Emma", age: 15},

  {name: "Matt", age: 16},

  {name: "Tom", age: 17}

];


function correctAge(people) {

  // Complete the function to return how many people are age 16+

}


ibeautiful
浏览 524回答 3
3回答

红颜莎娜

试试这个你会得到你的结果;var people = [{name:'Emma', age:15},{name:'Matt', age: 16}, {name:'Janet', age:17}];const correctAge = function(age) {&nbsp;return people.filter(x => x.age < age).length;}console.log(correctAge(16));

慕姐4208626

Array.reduce()是一个优雅的解决方案 -function correctAge(array) {&nbsp; return array.reduce((total, person) => {&nbsp; &nbsp; &nbsp; return person.age >= 16 ? ++total : total;&nbsp; &nbsp; }, 0)}对于问题中的示例,这将返回值 2。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript