Array.forEach内容覆盖问题求助:ES6 Fetch实现PageSpeed API调用
The Problem
Right now, your code replaces the entire contents of ulResults every time the forEach loop runs. Using innerHTML = completely overwrites whatever was in the element before, so by the end of the loop, only the last item in your results array gets displayed.
Solutions
Here are three reliable ways to fix this, each with their own use cases:
1. Append with innerHTML += (Quick & Simple)
Instead of replacing the content each time, append to it using +=. Just make sure to clear the container first if you might run this code multiple times (to avoid duplicate entries):
// Clear the container first to prevent duplicate content ulResults.innerHTML = ''; results.forEach(result => { ulResults.innerHTML += ` <section class="${result.lighthouseResult.configSettings.emulatedFormFactor}-strategy"> Your website overall ${result.lighthouseResult.configSettings.emulatedFormFactor} performance is ${result.loadingExperience.overall_category}. </section> `; });
2. Build HTML String First (Best Performance)
Frequent DOM updates can slow down your page, especially if you have a large number of results. Instead, build the full HTML string first, then update the DOM once:
// Use map to convert each result to HTML, then join into one string const resultsHTML = results.map(result => ` <section class="${result.lighthouseResult.configSettings.emulatedFormFactor}-strategy"> Your website overall ${result.lighthouseResult.configSettings.emulatedFormFactor} performance is ${result.loadingExperience.overall_category}. </section> `).join(''); // Update the DOM in one go ulResults.innerHTML = resultsHTML;
This approach is cleaner and more efficient because it minimizes the number of times the browser has to re-render the page.
3. Use insertAdjacentHTML (More Flexible)
If you prefer not to manipulate the entire innerHTML at once, you can append each section directly to the end of the container with insertAdjacentHTML:
// Clear the container first ulResults.innerHTML = ''; results.forEach(result => { ulResults.insertAdjacentHTML('beforeend', ` <section class="${result.lighthouseResult.configSettings.emulatedFormFactor}-strategy"> Your website overall ${result.lighthouseResult.configSettings.emulatedFormFactor} performance is ${result.loadingExperience.overall_category}. </section> `); });
The 'beforeend' position ensures each new section is added inside the container, right before its closing tag.
Quick Note on Semantics
You're using a <ul> element (ulResults) as the container, but rendering <section> elements inside it. For better HTML semantics, consider either:
- Changing the container to a
<div>or<section>, or - Replacing the
<section>tags with<li>to match the unordered list structure.
内容的提问来源于stack exchange,提问作者Augusto Mallmann

