简体   繁体   English

角度控制器数组为空,即使我刚刚定义了它

[英]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. “ alert(coffee.brand)”或数组的任何其他部分均显示“未定义”,显然不是。 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. 奇怪的是,未定义在for循环中打印正确的次数,因此它知道已填充数组,似乎无法读取数据。 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. 您正在错误地使用for in循环。 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循环,如下所示:

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. 有关for in循环的更多信息,请参见MDN上的文档。

You should update the for loop to 您应该将for循环更新为

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 供参考-http://plnkr.co/edit/bmuJmJO94mEzGuB3uF0K?p=preview

coffee is key not the object itself, so go like $scope.coffees[coffee]. 咖啡不是对象本身的关键,因此就像$ scope.coffees [coffee]。

For more information 欲获得更多信息

  • for...in loop for...in循环

    It iterates enumerable own and enumerable inherited properties. 迭代可枚举的自己和可枚举的继承属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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