gpt4 book ai didi

javascript - 为什么我的嵌套 for 循环中的代码不会被执行?

转载 作者:行者123 更新时间:2023-11-28 01:09:30 25 4
gpt4 key购买 nike

我有两个对象。一种包含大量有关人的数据(例如出生、姓名、出生地等),另一种包含字母表中每个字符的数组。我的目标是遍历我的人对象中的每个人,并将人名的第一个字母与字母表对象的属性进行比较。这样我就可以通过推送操作对字母表对象中的人名按字母顺序进行排序。这就是我想出来的。问题是,我的第二个循环中的代码不会被执行,而且我找不到问题。

angular.module('ArtistsCtrl', []).controller('ArtistsController', ['$scope', 'Artists', function ($scope, Artists) {

$scope.data = {};

$scope.tagline = 'A';

Artists.query(function (res) {
$scope.data.artists = res;
$scope.sortedNames = {A: [], B: [], C: [], D: [], E: [], F: [], G: [], H: [], I: [], J: [] , K: [], L: [], M: [], N: [], O: [], P: [], Q: [], R: [], S: [], T: [], U: [], V: [], W: [], X: [], Y: [], Z: []};
var sortedNamesProperties = Object.getOwnPropertyNames($scope.sortedNames);

(function () {
//loop to go through my artists array
for(var i = 0; i <= $scope.data.artists.length; i++){
//loop to go through my sortedNames array
for(var z = 0; z <= $scope.sortedNames.length; z++){
if($scope.data.artists[i].displayname.charAt(0) == sortedNamesProperties[z]){
$scope.sortedNames[z].push($scope.data.artists[i]);
break;
}
}
}
})()
});

}]);

编辑:

感谢您发布的所有可能性。我处理的是 obj 而不是数组的提示解决了它:)我用以下方式重写了代码,尽管它们可能是一些更好、更有效的处理方法。但非常感谢您的帮助。特别是@Andy

angular.module('ArtistsCtrl', []).controller('ArtistsController', ['$scope', 'Artists', function ($scope, Artists) {

$scope.data = {};

$scope.tagline = 'A';

Artists.query(function (res) {
$scope.data.artists = res;
$scope.sortedNames = {A: [], B: [], C: [], D: [], E: [], F: [], G: [], H: [], I: [], J: [] , K: [], L: [], M: [], N: [], O: [], P: [], Q: [], R: [], S: [], T: [], U: [], V: [], W: [], X: [], Y: [], Z: []};
var sortedNamesProperties = Object.getOwnPropertyNames($scope.sortedNames);

(function () {
//loop to go through my artists array
for(var i = 0; i <= $scope.data.artists.length; i++){
//loop to go through my sortedNames array
for(var z = 0; z <= Object.keys($scope.sortedNames).length; z++){
if($scope.data.artists[i].displayname.charAt(0) == sortedNamesProperties[z]){
$scope.sortedNames[sortedNamesProperties[z]].push($scope.data.artists[i]);
break;
}
}
}
})()
});

}]);

最佳答案

您可以将 $scope.sortedNames 对象的字段作为映射中的键来寻址,而不是嵌套循环:

function () {
//loop to go through my artists array
for (var i = 0; i < $scope.data.artists.length; i++) {
$scope.sortedNames[$scope.data.artists[i].displayname.charAt(0)].push($scope.data.artists[i]);
}
}

稍微简化的 fiddle :http://jsfiddle.net/9xeS8/1/

关于javascript - 为什么我的嵌套 for 循环中的代码不会被执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24655055/

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