访问节点中的数据字段给我未定义

时间:2019-05-06 21:15:21

标签: node.js

每当我尝试访问数据字段时,都会得到“未定义”日志,即使该数组似乎可以正常打印。

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

1 个答案:

答案 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