我正在使用对象文字并尝试访问嵌套数组并迭代循环,但它在我的控制台中不断显示 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);
});
关于javascript - 使用循环访问嵌套对象但有太多未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038628/