gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:48:03 25 4
gpt4 key购买 nike

在我的导航项指令中(最后一个):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com