过滤数组中的对象 (JavaScript)

DKX*_*KXP 1 javascript arrays object filter

有人可以帮助我理解为什么:

const people = [{
    name: "Carly",
    yearOfBirth: 1942,
    yearOfDeath: 1970,
  },
  {
    name: "Ray",
    yearOfBirth: 1962,
    yearOfDeath: 2011,
  },
  {
    name: "Jane",
    yearOfBirth: 1912,
    yearOfDeath: 1941,
  },
];



const findTheOldest = function(array) {
  let alivePeople = array.filter(function(person) {
    console.log(person.yearOfDeath);
    if (person.yearOfDeath === true) {
      console.log(person);
      return true;
    }
  });
  return alivePeople;
};

console.log(findTheOldest(people))
Run Code Online (Sandbox Code Playgroud)

正在显示https://i.stack.imgur.com/H3p5Q.png

我期望它返回 people 数组中的所有对象。我试图编写代码来过滤掉没有死亡一年的人。

hev*_*ev1 5

您的代码不起作用,因为对于数组中的任何对象person.yearOfDeath都不等于。true

您应该检查每个对象是否具有该属性,这可以使用、或运算符yearOfDeath来完成。如果不需要检查原型链,建议用于现代代码。Object.hasOwnObject#hasOwnPropertyinObject.hasOwn

const people = [{
    name: "Carly",
    yearOfBirth: 1942,
    yearOfDeath: 1970,
  },
  {
    name: "Ray",
    yearOfBirth: 1962,
    yearOfDeath: 2011,
  },
  {
    name: "Jane",
    yearOfBirth: 1912,
    yearOfDeath: 1941,
  },
  {
    name: "John",
    yearOfBirth: 2000
  }
];
let res = people.filter(o => Object.hasOwn(o, 'yearOfDeath'));
console.log(res);
Run Code Online (Sandbox Code Playgroud)