使用循环访问嵌套对象但未定义太多?

Accessing a nested object with loop but too many undefines?

我正在使用对象文字并尝试访问嵌套数组并遍历循环,但它在我的控制台中继续显示 59 次和 5 次未定义但随后显示数组。如何阻止它在控制台中执行未定义的操作?谢谢!

var votingData = {
  candidates: [{
  name: "Harry S. Truman",
  party: "Democratic"
},
{
  name: "Thomas E. Dewey",
  party: "Republican"
},
{
  name: "Strom Thurmond",
  party: "Dixiecrat"
}]

}

for(var candidate in votingData) {
  if(votingData.hasOwnProperty(candidate)) {
    for (let i = 0, j = votingData[candidate].length; i < j; i++) {
    console.log(votingData[candidate][i].name, votingData[candidate]
    [i].party);
   }
 }
}

您的 for/in 循环导致了问题,因为不需要它,因为 votingData 只包含一个 属性、candidates。因为只有一个属性,可以直接访问,不需要循环

您只需要遍历 votingData.candidates 属性 中的数组,为此,您可以使用您正在执行的标准计数 for 循环,或者,更好的是,使用 Array.forEach() 机制进行循环。它更好,因为它使您可以直接访问正在循环的数组元素,而无需索引器,并且可以使语法更加清晰,从而避免此类错误。

var votingData = {
  candidates: [{
  name: "Harry S. Truman",
  party: "Democratic"
},
{
  name: "Thomas E. Dewey",
  party: "Republican"
},
{
  name: "Strom Thurmond",
  party: "Dixiecrat"
}],
};

// Just loop through the arrays in the votingData.candidates property
votingData.candidates.forEach(function(candidate) {
  // Now "candidate" is an object, so standard "dot notation" to access
  // any/all properties of the current object is the way to go.
  console.log(candidate.name, candidate.party);
});

您的第一个 for 循环和 if 语句不是必需的。 你可能得到了很多 undefined 因为你有另一个 属性 被计算在 for-in 语句中。

如果您愿意,这里有一个不使用 forEach 的示例。

编辑

格式化数据以提高可读性

var votingData = {
  candidates: [
    {
      name: "Harry S. Truman",
      party: "Democratic"
    },
    {
      name: "Thomas E. Dewey",
      party: "Republican"
    },
    {
      name: "Strom Thurmond",
      party: "Dixiecrat"
    }
  ],
  not_candidates : []
}

for (let i = 0, j = votingData.candidates.length; i < j; i++) {
  console.log(votingData.candidates[i].name, votingData.candidates[i].party);
}