我不明白"(oldest.years || 0)"在此代码片段中的用法



我不明白为什么需要在oldest.years中使用"||0"。简单地使用oldest.years难道不够吗?此片段用于获得具有最高经验的飞行员。

var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];    
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});

如果oldest.years是falsy(例如未定义(,它将是0-一个数字

js中的比较运算符不仅适用于数字

最新更新