我在一个 Angular 应用程序中工作,在一个 Controller 中我需要迭代一个对象数组。这是 Controller 和这种情况涉及的代码:
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 Schools、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
我觉得这很简单,但我无法弄清楚它是什么(我对 Javascript 不是很熟练,抱歉)。谁能帮我解决这个问题?
预先感谢您的回答。
最佳答案
范围在登录函数中发生变化,因此变量 this
与之前不同,因为它在该函数中。
之前scope.login = function() {
你可以这样写:
var _this = this;
然后使用 _this.users.forEach(function(user) {
或for (var i = 0; i < _this.users.length; i++)
关于javascript 遍历对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293364/