Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

array[key] returns undefined, even though array[0] is defined, and key defined


In my nav item directive (the last one):

pantherDirectives.directive('bootstrapNavBar', function() {
    return {
        scope: {},
        templateUrl: 'partials/directives/bootstrapNavBar/wrapper.html',
        transclude: true,
        replace: true
    }
}).directive('navBarHeader', function() {
    return {
        scope: {},
        templateUrl: 'partials/directives/bootstrapNavBar/header.html',
        transclude: true,
        replace: true
    }   
}).directive('navBarBody', function() {
    return {
        scope: {},
        templateUrl: 'partials/directives/bootstrapNavBar/body.html',
        transclude: true,
        replace: true,
        controller: function($scope, $element) {
            this.items = [];
        }
    }   
}).directive('navBarDropDown', function() {
    return {
        scope: {},
        transclude: true,
        replace: true
    }   
}).directive('navItem', function() {
    return {
        scope: {},
        transclude: true,
        require: '^navBarBody',
        template: '<li ngclass="" ng-click="" ng-class="thisItem"><a data-ng-transclude></a></li>',
        replace: true,
        priority: 1000,
        controller: function($scope, $element, $attrs) {

        },
        link: function(scope, element, attrs, navBarBody) {
            var itemNum  = navBarBody.items.push(false);
            var thisItem = navBarBody.items[itemNum];

            console.log(itemNum);               //returns 1 then 2
            console.log(thisItem);             // returns undefined
            console.log(navBarBody.items[0]); //  returns false (as intended)
        }
    }
});

my key variable itemNum returns something, as does my array when I specify a number as the key, but when the key is my variable I get an undefined.


Solution

  • Array.push() returns the new length of the array. Thus, when you push an element into an empty array, you will be returned 1, but the element will be accessible at array[0] (0-indexed), and not array[1] which is how you are trying to access it.

    var arr = [];             // length is 0
    var len = arr.push(false);// returns 1 because array's new length is 1
    console.log(arr[0]);      // this works because what you pushed is at index 0
    console.log(arr[len]);    // won't work because you are essentially doing arr[1]
                              // i.e trying to access the second element (which doesn't exist)