使用forEach()遍历ICNDB API返回数组时出现forEach() is not a function错误
问题描述
我在遍历数组时遇到了forEach() is not a function错误。我知道forEach()仅适用于数组,代码中是对.value调用该方法,而.value本应是数组。我使用的数据源是ICNDB API,获取多个笑话的返回示例如下:
{ "type": "success", "value": [ { "id": 1, "joke": "Joke 1" }, { "id": 5, "joke": "Joke 5" }, { "id": 9, "joke": "Joke 9" } ] }
我的代码如下,尝试遍历response.value(看起来是数组)却报错,请问我遗漏了什么?
function getJokes(e) { const number = document.querySelector('input[type="number"]').value; const xhr = new XMLHttpRequest(); xhr.open("GET", `http://api.icndb.com/jokes/random/${number}`, true); xhr.onload = function() { if(this.status === 200) { const response = JSON.parse(this.responseText); let output = ''; if(response.type === 'success') { response.value.forEach(function(joke){ output += `<li>${joke.joke}</li>`; }); } else { output += '<li>Something went wrong</li>'; } document.querySelector('.jokes').innerHTML = output; } } xhr.send(); e.preventDefault(); }
问题原因与解决办法
问题出在当输入的number为1时,ICNDB API返回的value是单个对象而非数组,示例返回如下:
{ "type": "success", "value": { "id": 123, "joke": "Single joke here" } }
对象没有forEach()方法,因此调用时会触发错误。
以下是两种可行的解决办法:
方法一:判断类型后统一转为数组
修改代码中的遍历逻辑,先将response.value转为数组再遍历:
if(response.type === 'success') { const jokes = Array.isArray(response.value) ? response.value : [response.value]; jokes.forEach(function(joke){ output += `<li>${joke.joke}</li>`; }); }
方法二:用concat快速包装成数组
利用数组的concat方法自动处理数组和单个值的特性,直接包装后遍历:
if(response.type === 'success') { [].concat(response.value).forEach(function(joke){ output += `<li>${joke.joke}</li>`; }); }
两种方法都能保证无论请求1条还是多条笑话,都能正常遍历生成列表。
内容的提问来源于stack exchange,提问作者Suleyman Eminbeyli
相关产品推荐
相关产品推荐

