问题描述:

for (i = 0; i < roles.length; i++) {

Permission.defineRole(roles[i], function () {

console.log(roles[i]);

});

}

variable i is undefined.

How to get thats values?

网友答案:

Try this:

function executeCallback(role) {
    Permission.defineRole(role, function () {
        console.log(role);
    }
}
for (var i = 0; i < roles.length; i++) {

    executeCallback(roles[i]);
}

At the moment of execution of the callback, i might have changed (if the callback executes asynchcronously). Also as others noticed, you should add the keyword var (though that doesnt cause the undefined).

网友答案:

Can you change the definition of how your callback is executed? You might want to call your callback with the role parameter given, to avoid these closure issues.

Permission.defineRole = function(role, callback){
 //do stuff with your role
 //...

 //when you run the callback, add the role from this closure
 callback(role);
}

and then

for (i = 0; i < roles.length; i++) {
    // pass the roles[i] value to the new function, which creates a new scope for this iteration
    Permission.defineRole(roles[i], function (role) {
        // because role was passed down from the defineRole scope particular to that iteration, role is now the correct one, and different from roles[i].
        console.log(role);
    });
}

That said, if roles[i] is ever undefined, i probably isn't a value between 0 and the length of your array, or you simply assigned undefined to that key in the array.

It is also likely other code is changing i at the same time, since you did not use the var keyword to declare it (it's now on your global window object). Please use strict mode and use var to declare all variables, and window.name to add variables to the window object.

网友答案:

If you use strict mode, you MUST to declare the variable by keyword var.

Wrong code:

function d() {
    'use strict';
    asdf = 1;
}

Correct codes:

function d1() {
   'use strict';
    var asdf = 1;
}

function d2() {      
    asdf = 1;
}
相关阅读:
Top