数组返回undefined的API调用(Spotify应用) [英] Arrays returning undefined for API calls (spotify app)

查看:218
本文介绍了数组返回undefined的API调用(Spotify应用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我的工作,它使用Spotify的API,一个JavaScript的Web应用程序。我想在一个表中返回前5张专辑给定的艺术家。到目前为止,我得到的API调用工作,他们回到它显示一个艺术家的所有专辑没有特定的顺序表。我想表收缩的前5张专辑以人气,这是该表的第五列。

  VAR popsort =新的Array(新阵列());
    变种数= 0;    $(文件)。就绪(函数(){
    $(#搜索按钮)。点击(函数(){
        搜索();
    });
    ,
    功能搜索(){
        。VAR QUERY1 =的document.getElementById('querybox')值;
        $获得(https://api.spotify.com/v1/search?q=+ QUERY1 +&放大器;类型=艺术家,功能(数据){
            //alert(data.artists.items[0].id);
            getSeveralAlbums(data.artists.items [0] .ID);
        });
    }    功能getSeveralAlbums(artistid){
        //警报(artistid);
        $ .getJSON(https://api.spotify.com/v1/artists/+ artistid +/相册?album_type =专辑,
        功能(JSON){
            // BOB = json的;
            //console.log(json);
            的console.log(json.items.length);
            对于(VAR I = 0; I< json.items.length;我++){
                createArray(json.items [I] .href);
            }
            //console.log(count);
            popsort.sort(sortPopularity);
            //getAlbumInfo(json.items[i].href);
            getAlbumInfo(popsort);
        });
    }    功能getAlbumInfo(popsort){
        VAR TR;
        的console.log(popsort);
        // I< json.length
        //人气第一类型的数组。然后创建一个for循环并打印第5位。
        TR = $('< TR />');
        为(变量I = 0; I&小于5;我++){
            tr.append(&所述; TD>中+ popsort [I] [0] +&下; / TD>中); //专辑名称
            tr.append(&所述; TD>中+ popsort [I] [1] +&下; / TD>中); //艺人名称
            tr.append(&所述; TD>中+ popsort [Ⅰ] [2] +&下; / TD>中); // 发布日期
            tr.append(&所述; TD>中+ popsort [I] [3] +&下; / TD>中); //轨道数
            tr.append(&所述; TD>中+ popsort [I] [4] +&下; / TD>中); //流行
        }
        $('表')追加(TR);    }    功能createArray(albumhref){
        //console.log(albumhref);
        $ .getJSON(albumhref,
            功能(JSON){
                // I< json.length
                //人气第一类型的数组。然后创建一个for循环并打印第5位。
                的console.log(计数);
                popsort [计数] [0] .push(json.name);
                popsort [计数] [1] .push(json.artists [0]。名称);
                popsort [计数] [2] .push(json.release_date);
                popsort [计数] [3] .push(json.tracks.total);
                popsort [计数] [4] .push(json.popularity);
                ++计数;
                //警报(表编);
                //警报(表做);
            });
    }    功能sortPopularity(A,B){
        如果(一个[4] === B〔4]){
            返回0;
        }
        其他{
            返回(一个[4]所述; B [4])? -1:1;
        }
    }});

我用的是点击功能顶部从文本框获得艺术家姓名,传递到搜索函数返回一个 artistid 。我通过这个artistid到 getSeveralAlbums 的功能。在这个函数的JSON调用返回的HREFs而我想要在一个二维数组存储与普及沿特定艺术家的所有专辑。我的 sortPopularity 接近底部功能将理想排序这个数组由是人气,然后我计划通过此有序阵列( popsort ),其中有 getAlbumInfo 功能的for循环打印5倍,这将理想的打印<$ C $的前五个要素C> popsort 阵列。这个排序后,将理想成为艺术家的前5个最流行的专辑。

当我尝试运行此程序时,它返回undefined对于 popsort [计数] [0] .push(json.name)的错误;在 createArray 函数,并返回未定义的错误 tr.append(&LT; TD&gt;中+ popsort [I] [0] +&LT; / TD&gt;中); getAlbumInfo 功能。我在做什么错了?

更新:(新code)

  VAR popsort =新的Array(新阵列());
变种数= 0;
变种looopCount = 0;$(文件)。就绪(函数(){$(#搜索按钮)。点击(函数(){
    搜索();
});功能搜索(){
    。VAR QUERY1 =的document.getElementById('querybox')值;
    $获得(https://api.spotify.com/v1/search?q=+ QUERY1 +&放大器;类型=艺术家,功能(数据){
        getSeveralAlbums(data.artists.items [0] .ID);
    });
}功能getSeveralAlbums(artistid){
    $ .getJSON(https://api.spotify.com/v1/artists/+ artistid +/相册?album_type =专辑,
    功能(JSON){
        的console.log(json.items.length);
        looopCount = json.items.length;
        对于(VAR I = 0; I&LT; json.items.length;我++){
            createArray(json.items [I] .href);
        }
    });
}功能getAlbumInfo(popsort){
    VAR TR;
    //人气第一类型的数组。然后创建一个for循环并打印第5位。
    TR = $('&LT; TR /&GT;');
    为(变量I = 0; I&小于5;我++){
        tr.append(&所述; TD&gt;中+ popsort [I] [0] +&下; / TD&gt;中); //专辑名称
        tr.append(&所述; TD&gt;中+ popsort [I] [1] +&下; / TD&gt;中); //艺人名称
        tr.append(&所述; TD&gt;中+ popsort [Ⅰ] [2] +&下; / TD&gt;中); // 发布日期
        tr.append(&所述; TD&gt;中+ popsort [I] [3] +&下; / TD&gt;中); //轨道数
        tr.append(&所述; TD&gt;中+ popsort [I] [4] +&下; / TD&gt;中); //流行
    }
    $('表')追加(TR);}功能createArray(albumhref){
    $ .getJSON(albumhref,
        功能(JSON){
            如果(popsort.length&LT; =计数){
                popsort.push(新的Array());
            }
            //人气第一类型的数组。然后创建一个for循环并打印第5位。
            popsort [统计] .push(json.name);
            popsort [统计] .push(json.artists [0]。名称);
            popsort [统计] .push(json.release_date);
            popsort [统计] .push(json.tracks.total);
            popsort [统计] .push(json.popularity);
            ++计数;
            batchSort( - looopCount);
        });
}功能sortPopularity(A,B){
    如果(一个[4] === B〔4]){
        返回0;
    }
    其他{
        返回(一个[4]&GT; B [4])? -1:1;
    }
}功能batchSort(ⅰ){
    如果(ⅰ&下; = 0){
        popsort.sort(sortPopularity);
        getAlbumInfo(popsort);
    }
}
});


解决方案

首先,你在 createArray访问 popsort 未定义键() ,使用 .push()来代替。其次, getAlbumInfo(sortPopularity); 函数已经调用时第一个 $的getJSON(albumhref,FN ...); 效应初探尚未返回因此留给你一个空数组访问。 THT就是为什么你在访问时undefined,则返回 popsort

我会做的是我将创建一个递减计数器,并把它添加到的 createArray $。的getJSON()的回调,像这样的:

  VAR popsort =新的Array(新阵列());
    变种数= 0;
    变种looopCount = 0;    功能getSeveralAlbums(artistid){
        $ .getJSON(https://api.spotify.com/v1/artists/+ artistid +/相册?album_type =专辑,
        功能(JSON){
            的console.log(json.items.length);
            looopCount = json.items.length
            对于(VAR I = 0; I&LT; json.items.length;我++){
                createArray(json.items [I] .href);
            }
            //调用这两个popsort.sort(sortPopularity);和getAlbumInfo(popsort);之后所有的数据加载到popsort,不是在这里。
        });
    }    功能createArray(albumhref){
        $ .getJSON(albumhref,
            功能(JSON){
                如果(popsort.length&LT; =计数){
                    //如果popsort的长度小于计数,就意味着该索引(计数)被尚未popsort present
                    //推到与指数=计数增加项目popsort
                    popsort.push(新的Array());
                }
                popsort [统计] .push(json.name);
                popsort [统计] .push(json.artists [0]。名称);
                popsort [统计] .push(json.release_date);
                popsort [统计] .push(json.tracks.total);
                popsort [统计] .push(json.popularity);
                ++计数;                batchSort( - looopCount);
            });
    }    功能batchSort(ⅰ){
        如果(ⅰ&下; = 0){
            popsort.sort(sortPopularity);
            getAlbumInfo(popsort);
        }
    }});功能getAlbumInfo(popsort){
    为(变量I = 0; I&小于5;我++){
        tr.append(&所述; TR&GT;&下; TD&gt;中+ popsort [I] [0] +&下; / TD&gt;中); //专辑名称
        tr.append(&所述; TD&gt;中+ popsort [I] [1] +&下; / TD&gt;中); //艺人名称
        tr.append(&所述; TD&gt;中+ popsort [Ⅰ] [2] +&下; / TD&gt;中); // 发布日期
        tr.append(&所述; TD&gt;中+ popsort [I] [3] +&下; / TD&gt;中); //轨道数
        tr.append(&所述; TD&gt;中+ popsort [I] [4] +&下; / TD&GT;&下; / TR&gt;中); //流行
    }}

没有测试它虽然,但是这是思想..希望它帮助。

Hey guys I'm working on a Javascript web app which uses Spotify API. I'm trying to return the top 5 albums of a given artist in a table. So far I got the API calls working and they return a table which displays ALL the albums of an artist in no particular order. I'm trying to shrink the table to the top 5 albums based on "popularity" which is the fifth column of the table.

 var popsort = new Array(new Array());
    var count = 0;

    $(document).ready(function () {
    $("#searchbutton").click(function () {
        search();
    });
    ,
    function search() {
        var query1 = document.getElementById('querybox').value;
        $.get("https://api.spotify.com/v1/search?q=" + query1 + "&type=artist", function (data) {
            //alert(data.artists.items[0].id);
            getSeveralAlbums(data.artists.items[0].id);
        });
    }

    function getSeveralAlbums(artistid) {
        //alert(artistid);
        $.getJSON("https://api.spotify.com/v1/artists/" + artistid + "/albums?album_type=album",
        function (json) {
            //bob = json;
            //console.log(json);
            console.log(json.items.length);
            for (var i = 0; i < json.items.length; i++) {
                createArray(json.items[i].href);
            }
            //console.log(count);
            popsort.sort(sortPopularity);
            //getAlbumInfo(json.items[i].href);
            getAlbumInfo(popsort);
        });
    }

    function getAlbumInfo(popsort) {
        var tr;
        console.log(popsort);
        // i<json.length
        // Sort the array first by popularity. And then create a for loop and print the first five. 
        tr = $('<tr/>');
        for (var i = 0; i < 5; i++) {
            tr.append("<td>" + popsort[i][0] + "</td>"); // Album Name
            tr.append("<td>" + popsort[i][1] + "</td>"); // Artist Name
            tr.append("<td>" + popsort[i][2] + "</td>"); // Release Date
            tr.append("<td>" + popsort[i][3] + "</td>"); // Number of Tracks
            tr.append("<td>" + popsort[i][4] + "</td>"); // Popularity
        }
        $('table').append(tr);

    }

    function createArray(albumhref) {
        //console.log(albumhref);
        $.getJSON(albumhref,
            function (json) {
                // i<json.length
                // Sort the array first by popularity. And then create a for loop and print the first five. 
                console.log(count);
                popsort[count][0].push(json.name);
                popsort[count][1].push(json.artists[0].name);
                popsort[count][2].push(json.release_date);
                popsort[count][3].push(json.tracks.total);
                popsort[count][4].push(json.popularity);
                ++count;
                //alert("table compiled");
                //alert("Table done");
            });
    }

    function sortPopularity(a, b) {
        if (a[4] === b[4]) {
            return 0;
        }
        else {
            return (a[4] < b[4]) ? -1 : 1;
        }
    }

});

I use the click function at the top to get the artist name from a textbox, pass that into the "search" function which returns an artistid. I pass this artistid into the "getSeveralAlbums" functions. The json call in this function returns the hrefs to all the albums of a specific artist which I want to store in an 2D array along with the popularity. My "sortPopularity" function near the bottom will ideally sort this array by the fifth element which is "popularity" and then I plan to pass this sorted array (popsort) into the getAlbumInfo function which has a for loop printing 5 times, which will ideally print the first five elements of the popsort array. After sorting this will ideally be the top 5 most popular albums of an artist.

When I try to run this program, it returns an error undefined for both popsort[count][0].push(json.name); in the createArray function, and it returns an error undefined for tr.append("<td>" + popsort[i][0] + "</td>"); in the getAlbumInfo function. What am I doing wrong?

Update: (new code)

var popsort = new Array(new Array());
var count = 0;
var looopCount = 0;

$(document).ready(function () {

$("#searchbutton").click(function () {
    search();
});

function search() {
    var query1 = document.getElementById('querybox').value;
    $.get("https://api.spotify.com/v1/search?q=" + query1 + "&type=artist", function (data) {
        getSeveralAlbums(data.artists.items[0].id);
    });
}

function getSeveralAlbums(artistid) {
    $.getJSON("https://api.spotify.com/v1/artists/" + artistid + "/albums?album_type=album",
    function (json) {
        console.log(json.items.length);
        looopCount = json.items.length;
        for (var i = 0; i < json.items.length; i++) {
            createArray(json.items[i].href);
        }
    });
}

function getAlbumInfo(popsort) {
    var tr;
    // Sort the array first by popularity. And then create a for loop and print the first five. 
    tr = $('<tr/>');
    for (var i = 0; i < 5; i++) {
        tr.append("<td>" + popsort[i][0] + "</td>"); // Album Name
        tr.append("<td>" + popsort[i][1] + "</td>"); // Artist Name
        tr.append("<td>" + popsort[i][2] + "</td>"); // Release Date
        tr.append("<td>" + popsort[i][3] + "</td>"); // Number of Tracks
        tr.append("<td>" + popsort[i][4] + "</td>"); // Popularity
    }
    $('table').append(tr);

}

function createArray(albumhref) {
    $.getJSON(albumhref,
        function (json) {
            if (popsort.length <= count) {
                popsort.push(new Array());
            }
            // Sort the array first by popularity. And then create a for loop and print the first five. 
            popsort[count].push(json.name);
            popsort[count].push(json.artists[0].name);
            popsort[count].push(json.release_date);
            popsort[count].push(json.tracks.total);
            popsort[count].push(json.popularity);
            ++count;
            batchSort(--looopCount);
        });
}

function sortPopularity(a, b) {
    if (a[4] === b[4]) {
        return 0;
    }
    else {
        return (a[4] > b[4]) ? -1 : 1;
    }
}

function batchSort(i) {
    if (i <= 0) {
        popsort.sort(sortPopularity);
        getAlbumInfo(popsort);
    }
}
});

解决方案

First is that you are accessing undefined key of popsort in createArray(), use .push() instead. Second, the getAlbumInfo(sortPopularity); function is already called while the first $.getJSON(albumhref, fn...); reponse has not yet returned thus leaving you with an empty array to access. Tht is why you get an undefined return when accessing the popsort

What I would do is I will create a descending counter and add it to the createArray's $.getJSON() callback, like this:

var popsort = new Array(new Array());
    var count = 0;
    var looopCount = 0;

    function getSeveralAlbums(artistid) {
        $.getJSON("https://api.spotify.com/v1/artists/" + artistid + "/albums?album_type=album",
        function (json) {
            console.log(json.items.length);
            looopCount = json.items.length
            for (var i = 0; i < json.items.length; i++) {
                createArray(json.items[i].href);
            }
            // call both popsort.sort(sortPopularity); and getAlbumInfo(popsort); after all the data is loaded to popsort, not here.
        });
    }

    function createArray(albumhref) {
        $.getJSON(albumhref,
            function (json) {
                if (popsort.length <= count) {
                    // if the length of popsort is less than count, it means that that index(count) is not yet present in popsort
                    // push to add an item with index=count to popsort
                    popsort.push(new Array());
                }
                popsort[count].push(json.name);
                popsort[count].push(json.artists[0].name);
                popsort[count].push(json.release_date);
                popsort[count].push(json.tracks.total);
                popsort[count].push(json.popularity);
                ++count;

                batchSort(--looopCount);
            });
    }

    function batchSort(i) {
        if (i <= 0) {
            popsort.sort(sortPopularity);
            getAlbumInfo(popsort);
        }
    }

});

function getAlbumInfo(popsort) {
    for (var i = 0; i < 5; i++) {
        tr.append("<tr><td>" + popsort[i][0] + "</td>"); // Album Name
        tr.append("<td>" + popsort[i][1] + "</td>"); // Artist Name
        tr.append("<td>" + popsort[i][2] + "</td>"); // Release Date
        tr.append("<td>" + popsort[i][3] + "</td>"); // Number of Tracks
        tr.append("<td>" + popsort[i][4] + "</td></tr>"); // Popularity
    }

}

Haven't tested it though, but that's the thought.. Hope it helped.

这篇关于数组返回undefined的API调用(Spotify应用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆