如果数组为空而不是未定义,我如何 return 'null' 使用带有箭头函数的 .find 方法?

How do I return 'null' if the array is empty rather than undefined using the .find method with arrow functions?

我有一个函数,它接受一个人物对象数组,returns 是从特定数组中找到的第一个对象。在这种情况下 - 'isDoctor'。

const doctors = [ 
      { name: "`Jack Jones`", isDoctor: false},
      { name: "John Smith", isDoctor: true},
      { name: "Louise Young", isDoctor: false},
      { name: "David Boyle", isDoctor: true},
      { name: "Lisa Carr", isDoctor: false },
     ];


function findFirstDoctor(people) {
return people.find(person => person.isDoctor === true)
}

我写的代码正确return如下;但是,在存在空数组或所有 'isDoctor' 为假的情况下;我怎么会 return 'null' 而不是 undefined?

Object {
  isDoctor: true,
  name: "John Smith"
}

如果你想为此使用 .find,你必须明确分配或 return null 自己,如果没有找到:

const doctors = [ 
];

function findFirstDoctor(people) {
  const foundDoctor = people.find(person => person.isDoctor === true)
  return foundDoctor || null;
}

console.log(findFirstDoctor(doctors));

您可以使用 || 提供特定的 "falsy" 值:

function findFirstDoctor(people) {
  return people.find(person => person.isDoctor === true) || null;
}

(另外:我建议不要使用 ===true 进行显式测试,除非你 真的 因为你的数据模型需要这样做。如果 .isDoctor 旨在成为一个布尔标志,那么您真正需要的只是 person => person.isDoctor。)

无论如何,在末尾添加 || null 利用了 .find() 将 return 一个对象,如果它确实找到了某些东西,而那永远不会 "falsy"。因此,计算 || 远端代码的唯一方法是在 .find() returns undefined 时,因此您可以替换 null.

我个人认为在大多数情况下区分 nullundefined 只是另一种脆弱的编码实践。 ==!= 运算符在与 nullundefined 进行比较时,始终将两者视为等效。