javascript - array[key] 返回未定义,即使 array[0] 已定义且 key 已定义

标签 javascript 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返回一些东西,当我指定一个数字作为键时,我的数组也会返回一些东西,但是当键是我的变量时,我得到一个未定义

最佳答案

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)

关于javascript - array[key] 返回未定义,即使 array[0] 已定义且 key 已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21522534/

相关文章:

javascript - ngRepeat 与其他指令结合

php - 有没有一种简单的方法使用 CSS 或 Javascript 根据字段的值更改 div 的背景颜色

javascript - 如何在 X 轴上方显示 Y 轴?

javascript - 使用 Angular $post 和 PHP Codeigniter 请求和响应

javascript - 有没有更干净的方法在 AngularJS html View 中执行 if else 语句?

angularjs - AngularJS 中 html5 音频元素的 ng-model

javascript - 在 Angularjs 中显示独特的下拉选项

javascript - jQuery slideToggle - 仅 slideUp Action 的回调函数

javascript - 将 JavaScript 对象的可变长度对象的属性连接到该对象的新属性中

css - Angular Bootstrap 动画选项卡过渡但不过渡