Javascript json demo
- Why are the para1.textContent = motherInfo; and para2.textContent = kittenInfo; lines inside the displayCatInfo() function, and not at the end of the script? This has something to do with async code.
const section = document.querySelector('section'); let para1 = document.createElement('p'); let para2 = document.createElement('p'); let motherInfo = 'The mother cats are called '; let kittenInfo; fetch('sample.json') .then(response => response.text()) .then(text => displayCatInfo(text)) function displayCatInfo(catString) { let total = 0; let male = 0; // Add your code here let items = JSON.parse(catString) for (let i = 0; i < items.length; i++){ motherInfo += ' ' + items[i]['name'] if (i===items.length -2){ motherInfo += ' and ' }else if(i < items.length -2){ motherInfo += ',' } for (let j=0; j <items[i]['kittens'].length; j++){ total++; if (items[i]['kittens'][j]['gender'] === 'm'){ male++ } } } kittenInfo = 'There is ' + total +' kittens, '+ male+ ' are male '; // Don't edit the code below here! para1.textContent = motherInfo;
para2.textContent = kittenInfo; } section.appendChild(para1); section.appendChild(para2);
阅读量: 615
发布于:
修改于:
发布于:
修改于: