简体   繁体   中英

TypeError: Cannot read property '0' of undefined AngularJS

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

        var value = value[i];
        console.log(value);

    }

Really confused how this could possibly be wrong...

'i' is defined at zero so not sure how it could not find the value.

Below is the whole of my controller code.

 angular.module(module.name).controller(module.name + '.c.' + current.name, [
        '$scope',
        '$stateParams',
        'members',
        'assessment', 
        '$localStorage',  

    function (scope, stateParams, members, assessment, $localStorage) {
        scope.members = members;        
        // Asessment and item scope variables
        scope.assessment = assessment;             

        scope.active = $localStorage.$default({
            value : false
        });  

        console.log(members.length);      

        // This isn't doing anything much atm apart from firing the 
        // console logs
        scope.change = function (active) {

            if (active) {
                scope.active = $localStorage.$default({
                    value : true
                });
                console.log('hi 1');
            } else {
                scope.active = $localStorage.$default({
                    value : false
                });
                console.log('hi 2');
            }
        };   

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

            var value = value[i];
            console.log(value);
        }
    }
]);

UPDATE

This is what I was after:

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

        value = "value" + i;

        console.log(value);
}          

As far as I can see, the value has either true or false . So you need to remove the line:

value = value[i];

I guess you are trying to do, as the members is the one that has an array of values. Please change your code to:

value = members[i];

According to your comment on previous answer you may want like this

for ( var i = 0; i < members.length; i++ ) {
        console.log('value' + i);
}

so output will be:

value0

value1

value2

.....

and if you want to show member values

for ( var i = 0; i < members.length; i++ ) {
     console.log(members[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM