每当我尝试访问数据字段时,都会得到“未定义”日志,即使该数组似乎可以正常打印。
const users = [];
app.get('/users', function(req, res, next) {
res.render('users', {
ListOfNames: users,
pageTitle: 'active users'
});
console.log(users);
for (let user in users) {
console.log(user.userName);
}
});
app.post('/add-user', function(req, res, next) {
users.push({ userName: req.body.user });
});
输出:
[ { userName: '1' },
{ userName: '12' },
{ userName: '123' },
{ userName: '1234' } ]
undefined
undefined
undefined
undefined
答案 0 :(得分:2)
for (let user in users)
应该是for (let user of users)
。
for/in
遍历对象键,通常与对象一起使用。
let obj = { a: 1, b: 2, c: 3 }
for (let key in obj) { console.log(key) } // a, b, c
for/of
遍历可迭代的值,通常用于数组。
let arr = [1, 2, 3]
for (let val of arr) { console.log(val) } // 1, 2, 3