简体   繁体   中英

angular controller array empty even though i just defined it

the following is a function in an angular controller. "alert (coffee.brand)", or any other part of the array, prints "undefined," which obviously it isn't. The weird part is, undefined prints the correct number of times in the for loop, so it knows the array is populated, it just can't seem to read the data. thoughts? Thanks in advance!

$scope.activate = function(id){


            $scope.coffees =
    [
    {'id': 1,
    'brand': 'Folgers',
    'name': 'Regular',
    'country': 'America',
    'reviews': [
            {'rating': 3,
            'comment': "gross",
            'reviewer': "James"
            }
    ]
    },
    {'id': 2,
    'brand': 'Starbucks',
    'name': 'Mocha',
    'country': 'America',
    'reviews': [
    {'rating': 7,
    'comment': 'insane!',
    'reviewer': 'Bob'
    },
    {'rating': 5,
    'comment': 'solid...',
    'reviewer': 'Joe'
    }
    ]
    }
    ];

            for (coffee in $scope.coffees){                       

                    alert (coffee.brand);
                    if (coffee.id == id){
                            $scope.currCoffee = coffee;
                            alert("here")
                            alert ($scope.currCoffee.id);
                    }
            }

    };

You are using the for in loop incorrectly. It does not iterate over elements in an array, but property names of an object. In your case, as you are using an implicitly numerically indexed array, it would be better to use a normal for loop, like so:

for (var i = 0; i < $scope.coffees.length; i++) {        
    var coffee = $scope.coffees[i];               
    alert (coffee.brand);
    if (coffee.id == id){
        $scope.currCoffee = coffee;
        alert("here")
        alert ($scope.currCoffee.id);
    }
}

See the documentation over at MDN for more information about the for in loop.

You should update the for loop to

for (var i = 0; i < $scope.coffees.length; i++) {

and retrieve values like

alert($scope.coffees[i].brand);

For reference - http://plnkr.co/edit/bmuJmJO94mEzGuB3uF0K?p=preview

coffee is key not the object itself, so go like $scope.coffees[coffee].

For more information

  • for...in loop

    It iterates enumerable own and enumerable inherited properties.

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