我正在Angular应用程序中工作,并在控制器内工作,我需要迭代对象数组。这是控制器以及参与这种情况下,代码:javascript遍历对象数组
myapp.controller('LoginController', ['$scope', function(scope) {
// Users for test
this.users = [
{
name: 'admin',
password: 'admin',
role: 'ADMIN'
},
{
name: 'employee',
password: '12345',
role: 'EMPLOYEE'
}
];
console.dir(this.users); // Prints an array of objects correctly
// called when user submits
scope.login = function() {
console.log('login(). User: ');
console.dir(scope.user); // Prints the object with user's input (also correct)
var found = false;
for(let u of this.users) {
console.log('Comparing with:');
console.dir(u);
if(u.name == scope.user.name && u.password == scope.user.password) {
console.log('Found!');
found = true;
// do something else...
}
}
if(!found) { // show error message... }
}
}]);
的问题是,当我提交登录表单(来电scope.login()
)我在控制台收到一条错误消息:
TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
at m.scope.login (loginController.js:44)
...
loginController.js:44
对应for(let u of this.users) {
一行。我通过网络进行搜索(W3学校,MDN和这个网站),但解决方案并没有为我工作。我已经尝试以下解决方案:
for(var u of this.users)
var u; for(u in this.users)
for(var i = 0; i < this.users.lenght; i++)
:这改变了错误消息Cannot read property 'length' of undefined
我觉得它的东西简单,但我cant't图搞清楚它是什么(我对Javascript不熟练,对不起)。任何人都可以帮我解决这个问题吗?
在此先感谢您的答案。
是'this.users'不确定? –
你为什么使用'this'?你是否应该不使用'scope'或者只是一个普通的'var'或'let'?因为当你到达函数时,'this'引用函数 – Chifilly
@Chifilly它是'controller as'语法。它倾向于'$ scope' – mhodges