奇怪的角度问题 - 尽管定义了数组[0]并且键定义了,但数组[key]返回undefined

时间:2014-02-03 08:20:15

标签: javascript arrays angularjs angularjs-directive angularjs-scope

我有角度的奇怪问题。在我的导航项目指令(最后一个)中:

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)
        }
    }
});

我的键变量itemNum返回一些内容,当我指定一个数字作为键时,我的数组也会返回,但当键是我的变量时,我得到一个未定义的

1 个答案:

答案 0 :(得分:4)

Array.push()返回数组的新长度。因此,当您将一个元素推入一个空数组时,您将返回1,但该元素可以在array[0](0索引)访问,而不是array[1],这是如何你正试图访问它。

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)