I'm facing this error when I am trying to loop over an array. Now I know that forEach() only works with arrays, and in my code, I'm using it on .value which is an array. I'm using this website to fetch the data:https://www.icndb.com/api/
Example output when fetching multiple jokes:
{ "type": "success", "value": [ { "id": 1, "joke": "Joke 1" }, { "id": 5, "joke": "Joke 5" }, { "id": 9, "joke": "Joke 9" } ] }
As you can see in my code below, I'm trying to loop over response.value
, which seems to me an array. What is it that I'm missing?
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();
}