简体   繁体   English

一元运算符 in.reduce() function

[英]Unary operator in .reduce() function

I was reading a medium article and came across this code.我正在阅读一篇中等文章并遇到了这段代码。 It returns the object with the most experienced pilot using .reduce() .它使用 .reduce .reduce()返回 object 和最有经验的飞行员。 I can't wrap my head around the expression (oldest.years || 0) .我无法理解表达式(oldest.years || 0) Why not just use (oldest.years ) ?为什么不直接使用(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;
}, {});

console.log(mostExpPilot);

When we look at the documentation of Array.reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#parameters we can see that this is because the example code has an initialValue of {} which has no years property.当我们查看Array.reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#parameters的文档时,我们可以看到这是因为示例代码有{}initialValue值,没有years属性。

Same would be:同样是:

var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return oldest.years > pilot.years ? oldest : pilot;
}, { years: 0});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM