How do I convert a for of loop into a for loop? This is so that I can avoid/ solve the eslint error message.I have tried googling, but the solution I am getting is to disable/configure eslint. Help me understand what I'm missing. here is the error message. " error iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations "
here is my working code using the for of.
let str = '';
const arr = [];
for (const person of featuredObject) {
str = `
<div ><img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>
</div>`;
arr.push(str);
}
here is my failed implementation of the for loop.
let str = '';
const person = '';
const arr = [];
for (let i = 0; i < featuredObject.length; i = 1) {
str= `
<div ><img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>
</div>`;
arr.push(str);
}
CodePudding user response:
let str = "";
const arr = [];
for (let i = 0; i < featuredObject.length; i = 1) {
const person = featuredObject[i];
str = `
<div ><img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>
</div>`;
arr.push(str);
}
Better way
const arr = featuredObject.map((person) => {
const str = `
<div ><img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>
</div>`;
return str;
});
CodePudding user response:
In for of loop in person is a element of featuredObject, so it as all properties but in for loop person is string not an element featuredObject. I am using div element because if you append a element into another element it preserve all event listener but when you append something into innerHTML it removes all event listener.
const arr = [];
for (let i = 0; i < featuredObject.length; i ) {
const person = featuredObject[i];
const div = document.createElement("div");
div.setAttribute("class", "portfolio");
div.innerHTML = `
<img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>`;
arr.push(div);
}
CodePudding user response:
Use map to generate the new array.
const arr = featuredObject.map((person) => `
<div ><img src=${person.image} alt="#"></div>
<div >
<h3 >${person.Name}</h3>
<p >${person.title}</p>
<p >${person.description}</p>
</div>
</div>`);