我正在尝试从下面的代码中解决两个问题。
var employees = [
{
firstName: "John",
lastName :"Doe",
qualification: {Diploma: 'IT Software' , Degree: 'Software Engineering'}
},
{
firstName:"Anna",
lastName:"Smith",
qualification: {Diploma: 'Business Accountant' , Degree: 'Business Administration'}
}
];
for(var i in employees)
{
console.log(employees[i]);
}
以上代码的输出如下。
[object Object] {
firstName: "John",
lastName: "Doe",
qualification: [object Object] {
Degree: "Software Engineering",
Diploma: "IT Software"
}
}
[object Object] {
firstName: "Anna",
lastName: "Smith",
qualification: [object Object] {
Degree: "Business Administration",
Diploma: "Business Accountant"
}
}
我希望索引输出而不是[object object]它应该为相应的对象显示[index:1]和[index:2]。
我们将不胜感激。 感谢
答案 0 :(得分:0)
不要使用for-in
(没有安全措施)来遍历数组(details and alternatives listed in this answer),这不是它的用途。
如果您想在数组中同时使用对象及其索引,那么最好的选择是forEach
:
employees.forEach(function(employee, i) {
console.log("[index: " + (i + 1) + "]");
// And if you need the actual employee object,
// it's `employee`
});
注意i + 1
:JavaScript中的索引(以及一般的编程)通常以0
开头,而不是1
,因此为了获得所需的输出,我们在索引中添加一个。
或者,一个无聊的旧for
循环:
for(var i = 0; i < employees.length; ++i)
{
console.log("[index: " + (i + 1) + "]");
// And if you need the actual employee object, as
// with your code, it's `employees[i]`
}
答案 1 :(得分:0)
当您在for bucle中循环数组时,您将获得带有变量 i 的索引
for(var i in employees)
console.log("index:"+ i);