練習 12 - 找到最舊的
給定一組代表具有出生和死亡年份的人的物件,回傳最年長的人的名字。
提示
- 這可以通過幾個鏈式陣列方法來完成,或者使用
reduce.
我想使用reduce方法
const people = [
{
name: 'Carly',
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
const findTheOldest = function (arr) {
const oldestPerson = arr.reduce((accumulator, next) => {
const age1 = accumulator.yearOfDeath - accumulator.yearOfBirth;
const age2 = next.yearOfDeath - next.yearOfBirth;
if (age1 > age2) {
return accumulator.name;
} else {
return next.name;
}
});
return oldestPerson;
};
console.log(findTheOldest(people));
uj5u.com熱心網友回復:
只是稍微更正了您的代碼
const people = [
{name: 'Carly', yearOfBirth: 1942, yearOfDeath: 1970,},
{name: 'Ray', yearOfBirth: 1962, yearOfDeath: 2011,},
{name: 'Jane', yearOfBirth: 1912, yearOfDeath: 1941,},
];
const findTheOldest = function (arr) {
if (arr.length === 0) return null;
if (arr.length === 1) return arr[0].name;
const getAge = ({ yearOfDeath, yearOfBirth }) => yearOfDeath - yearOfBirth;
const oldestPerson = arr.reduce((acc, next) => (getAge(acc) > getAge(next)) ? acc : next);
return oldestPerson.name;
};
console.log(findTheOldest(people));
.as-console-wrapper { max-height: 100% !important; top: 0 }
uj5u.com熱心網友回復:
現在它作業正常。
const people = [
{
name: 'Carly',
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
const findTheOldest = function (arr) {
const oldestPerson = arr.reduce((accumulator, next) => {
const age1 = accumulator.yearOfDeath - accumulator.yearOfBirth;
const age2 = next.yearOfDeath - next.yearOfBirth;
if (age1 > age2) {
return accumulator;
} else {
return next;
}
});
return oldestPerson.name;
};
console.log(findTheOldest(people));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/503665.html
標籤:javascript 数组 目的
上一篇:為什么我不能使用jquery和“forin”迭代JSON以回傳物件和陣列字串?
下一篇:如何將行轉置為值陣列中的列?
