简体   繁体   English

为什么我在地图箭头功能中总是收到未定义的错误?

[英]Why I keep getting undefined error in map arrow function?

I recently just started on a project that utilizes Spotify API. 我最近刚开始一个利用Spotify API的项目。 I've been trying to extract artist's IDs with the code I wrote: 我一直在尝试用我编写的代码提取艺术家的ID:

app.events = function() {
$('form').on('submit', function(e) {
    e.preventDefault();
    let artists = $('input[type=search]').val();
    artists = artists.split(',');
    let search = artists.map(artistName => app.searchArtist(artistName));
    $.when(...search)
        .then((...results) => {
            results = results.map(res => res[0].artists.items[0].id);
            console.log(results);
        });
});


app.searchArtist = (artistName) => $.ajax({
url: 'https://api.spotify.com/v1/search',
headers: {
    'Authorization': 'Bearer ' + accessToken
},
method: 'GET',
dataType: 'json',
data: {
    type: 'artist',
    q: artistName
}

The problem is with this line: 问题在于此行:

results = results.map(res => res[0].artists.items[0].id);

Every time I try to run the code, it returned res[0] is undefined, as shown like this in browser's console: res[0] undefined 每次我尝试运行代码时,返回的res[0]是未定义的,如在浏览器控制台中所示: res [0] undefined

The array that I'm trying to get is artist ID as shown: artist id 我要获取的数组是艺术家ID,如下所示: 艺术家ID

I don't know why it keeps getting the undefined error. 我不知道为什么它不断收到未定义的错误。 I'm new to javascript and using API. 我是Java语言和API的新手。 What is the reason for this error? 此错误的原因是什么? Help please. 请帮助。

The problem seems to be trying to access res[0] when there's no 0 key in res . res中没有0键时,问题似乎是试图访问res [0]。

You should try this approach: 您应该尝试这种方法:

results = results.map(res => res.artists.items[0].id);

The way Array.prototype.map() works is by calling the specified function for each element in the array and returning the new array without modifying the original. Array.prototype.map()的工作方式是通过为数组中的每个元素调用指定的函数并返回新数组而不修改原始数组。

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

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