我接到了一项任务,我一定是遗漏了什么。提供的代码不是原始问题,而是相似的。我必须计算阵列中有多少人年龄在 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+}
3 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
试试这个你会得到你的结果;
var people = [{name:'Emma', age:15},{name:'Matt', age: 16}, {name:'Janet', age:17}];
const correctAge = function(age) {
return people.filter(x => x.age < age).length;
}
console.log(correctAge(16));
慕姐4208626
TA贡献1852条经验 获得超7个赞
Array.reduce()是一个优雅的解决方案 -
function correctAge(array) {
return array.reduce((total, person) => {
return person.age >= 16 ? ++total : total;
}, 0)
}
对于问题中的示例,这将返回值 2。
添加回答
举报
0/150
提交
取消