在我的导航项指令中(最后一个):
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/