如何使用函数、for 循环和条件语句访问数组中对象的属性?

How can I access the prop of the objects in an array with function, for loop and a conditional statement?

我很想知道如何通过使用函数、for 循环和条件语句访问 属性 嵌套在数组中的对象。

const details = [
  {
    first: "Liverpool",
    second: 'Man City',
    third: 'Chelsea',
    fourth: 'Tottenham',
    similarity: 'EPL'
  },
    {
    first: "Real Madrid",
    second: 'Barcelona',
    third: 'Villareal',
    fourth: 'Sevilla',
    similarity: 'La Liga'
  }
]



function team(name,prop){
  for (let i = 0; i < details.length; i++){
    if(details[i].first === name && details[i].name[prop] === prop){
      return true;
    } else {
      return false;
    }
  }
}

console.log(team('Liverpool','EPL'));

这不是主要代码,但应该可以。我正在尝试检查函数调用中传递的第二个参数是否是其中一个对象的 属性。如果它是其中之一,它应该 return true 如果不是,它应该 return false。 对我来说,主要问题在第 22 行: ....details[i].name[prop] === prop)

我真的不知道该怎么做。请帮忙。

如果想法是始终比较相似性,则方法为:

function team(name,prop){
  for (let i = 0; i < details.length; i++){
    if(details[i].first === name && details[i].similarity === prop){
      return true;
    } else {
      return false;
    }
  }
}
team('Liverpool', 'EPL')

但是如果 属性 可以是动态的,它将是:

function team(name, prop, cup){
  for (let i = 0; i < details.length; i++){
    if(details[i].first === name && details[i][prop] === cup){
      return true;
    } else {
      return false;
    }
  }
}
team('Liverpool', 'similarity', 'EPL')

另一种方法是,如果你想遍历所有的名字,那么它可以是这样的:

function team(name,prop){
  for (let i = 0; i < details.length; i++){
    const teams = Object.entries(details[i])
    const similarity = details[i].similarity;

    for (let j = 0; j < teams.length; j++){
      if (teams[j][1] === name && similarity === prop){
        return true;
      }
    }

  }
  return false;
}
team('Man City', 'EPL')

希望对您有所帮助。