我有一个包含三个人对象的数组。我正在尝试使用in运算符打印每个对象,而不是对象我得到每个对象的索引值(0,1,2)。以下是我的代码。任何帮助将是欣赏。
var persons = [{
name: "user1",
password: "password1"
}, {
name: "user2",
password: "password2"
}, {
name: "user3",
password: "password3"
}]
for (var person in persons) {
console.log(person)
}
答案 0 :(得分:1)
这与角度无关,这是一个JavaScript问题。
for...in
关键字循环对象中的键,而不是值。这通常用于实际对象,而不是数组:
let person = {
name: "user1",
password: "password1"
}
for (k in person) {
console.log('person[' + k + '] =', person[k])
}

要遍历数组,您可以使用原生的常规for
或数组的forEach
方法:
let people = [{
name: "user1",
password: "password1"
}, {
name: "user2",
password: "password2"
}]
for (let i = 0; i < people.length; ++i) {
console.log('people[' + i + '] =', JSON.stringify(people[i]))
}
people.forEach((person, idx) => {
console.log('person ' + idx + ' =', JSON.stringify(person))
})
&#13;
答案 1 :(得分:0)
尝试使用forEach
angular.forEach(persons,function(person,key){
console.log(key);
})