0

I am stepping through the AngularJS code below in the debugger. It says testingWhat is of type Array[1], but when I try to access it using [0], testingArray becomes of type undefined, with no content. Why?

myApp.controller('SomeController', function ($scope, MyData) {
    $scope.dataForTheTree = MyData.collection;
    var testingWhat = MyData.collection;
    var testingArray = MyData.collection[0];
    for(var x in testingWhat) {
        console.log("Loading data into tree: " + x);
    }
});
Mattias
  • 1,110
  • 1
  • 11
  • 26

1 Answers1

1

If console.log(testingArray) is undefined then the first object in the collection is undefined .. you essentially have an array like:

var array = [undefined];

It will have a length .. array[0] will be undefined.

On another note, never ever use for in to iterate over an array. It could iterate over properties of the array or you could get the items in the wrong order.

Always use the for loop. Here is a more detailed answer:

Community
  • 1
  • 1
sirrocco
  • 7,975
  • 4
  • 59
  • 81