-
-
Save wiledal/3c5b63887cc8a010a330b89aacff2f2e to your computer and use it in GitHub Desktop.
/* | |
Template literals for-loop example | |
Using `Array(5).join(0).split(0)`, we create an empty array | |
with 5 items which we can iterate through using `.map()` | |
*/ | |
var element = document.createElement('div') | |
element.innerHTML = ` | |
<h1>This element is looping</h1> | |
${Array(5).join(0).split(0).map((item, i) => ` | |
<div>I am item number ${i}.</div> | |
`).join('')} | |
` | |
/* | |
Results: | |
<div> | |
<h1>This element is looping</h1> | |
<div>I am item number 0.</div> | |
<div>I am item number 1.</div> | |
<div>I am item number 2.</div> | |
<div>I am item number 3.</div> | |
<div>I am item number 4.</div> | |
</div> | |
*/ |
@efectusmagnus Clever solution. Thanks
Always use for or while loop instead of map. Map has no use here and is not to replace "normal" loops.
Map takes an array (allocated), and returns an array (allocated at some time) again.
When you use Map, you like it because it looks cool and code is shorter. But it is not it's purpose and any other developer would not like it.
just an advice, because this is really a good example of: me thinking my code is cool, think of others and favor simplicity.
this is how it should be done in December 2022:
const htmlOutput = '';
for (let i=0; i<5; i++) {
htmlOutput += `<div>I am item number ${i}.</div>`
}
// then you do your dom ops:
var element = document.createElement('div')
element.innerHTML = htmlOutput;
isn't simpler better ?
Thanks WILEDAL;
@bacloud23
When you use Map, you like it because it looks cool and code is shorter. But it is not it's purpose and any other developer would not like it.
Except, you know, the entire React community 👀
I used this to loop through my dots:
And this is the output:
You can check it out in Codepen.