简体   繁体   English

JavaScript数组元素未定义

[英]Javascript array element undefined

I am trying out some angularjs stuff. 我正在尝试一些angularjs的东西。 So I have a few arrays. 所以我有几个数组。 One of them is artists. 其中一位是艺术家。 this is it's basic structure from console.log(artists); 这是console.log(artists);的基本结构console.log(artists);

artists 艺术家

problem is that I can't access the elements of the array individually. 问题是我无法单独访问数组的元素。 I read up a lot of things regarding associative arrays and may questions on SO but none really helped. 我阅读了很多有关关联数组的内容,可能对SO提出了疑问,但没有一个真正的帮助。 So either it is a very silly mistake I am making or it is some thing else. 因此,这或者是我犯的一个非常愚蠢的错误,还是另一回事。

Here are few results that I got with every array I have. 这是我拥有的每个数组的一些结果。

console.log(artists[0]);  //returns undefined
console.log(artists['0']); //returns undefined
console.log(artists.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray(artists)); //returns true

And yes I created the array like this in a service, ChartService 是的,我在ChartService服务中创建了这样的数组

var artists = [];
var artistids = [];
var tracks = [];

$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
        var items = data.artists.items;
        items.forEach(function(item){
            artists.push(item.name);
            artistids.push(item.id);
            var query = trackApi+item.id+'/top-tracks?country=SE'

            $http.get(query).success(function (response) {
                tracks.push({'preview': response.tracks[0].preview_url});

            });
        });


});

return {
  Artists : artists,
  Tracks : tracks
  }

And my controller 还有我的控制器

console.log(ChartService.Artists); //runs fine
console.log(ChartService.Tracks); //runs fine

 $scope.tracks = ChartService.Tracks;

 console.log($scope.tracks);  //runs fine
 console.log($scope.tracks[0]);  //returns undefined
console.log($scope.tracks['0']); //returns undefined
console.log($scope.tracks.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray($scope.tracks)); //returns true

The issue is that you check the content of artists before the issued http get requests have triggered their responses. 问题是您在发出的http get请求触发其响应之前检查artists的内容。

One way to resolve that is to put your code in the success callback, like this: 解决该问题的一种方法是将代码放入success回调中,如下所示:

$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
    var items = data.artists.items;
    items.forEach(function(item){
        artists.push(item.name);
        artistids.push(item.id);
        var query = trackApi+item.id+'/top-tracks?country=SE'

        $http.get(query).success(function (response) {
            tracks.push({'preview': response.tracks[0].preview_url});
        });
    });
    // here 
    console.log(artists);
});

Still, that solves it for artists , but then you'd need to do something similar if you need the tracks : as you have more then one request providing for that, you'd need to check the length of the tracks array and only if it has the complete length, like this: 尽管如此,这对于artists还是可以解决的,但是如果您需要tracks ,那么您就需要做类似的事情:由于您需要提供多个请求,因此您需要检查tracks数组的长度,并且仅当它具有完整的长度,如下所示:

$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
    var items = data.artists.items;
    items.forEach(function(item){
        artists.push(item.name);
        artistids.push(item.id);
        var query = trackApi+item.id+'/top-tracks?country=SE'

        $http.get(query).success(function (response) {
            tracks.push({'preview': response.tracks[0].preview_url});
            if (tracks.length == items.length) { // all done
                console.log(artists, tracks);
            }
        });
    });
});

In a follow-up question (in comments) you explained you need this in your controller. 在后续问题中(在评论中),您解释了您需要在控制器中使用它。 You might look into $watch or variants of that method. 您可能会研究$watch或该方法的变体。 If you need assistance with that, I would suggest to ask a new question. 如果您需要帮助,我建议问一个新问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM