-
-
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> | |
*/ |
I simplified the code and made it more elegante (maybe?).
// Magic number +1 is for Array[0], which never receives any value, in this kind of logic.
Array(5 + 1).fill('').reduce((finalMarkup) => finalMarkup + `stuff to be repeated \n`);
This snippet can scale, as long as you use the reduce()
method correctly.
I used this to loop through my dots:
const dotClick = document.createElement('div');
dotClick.innerHTML = `
<div class="dot-ctn">
${Array(8).fill().map((item, i) => `
<span class="dot" onclick="currentSlide(${i+1})" tabindex="0"></span>
`).join('')}
</div>
`
And this is the output:
<div class="dot-ctn">
<span class="dot" onclick="currentSlide(1)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(2)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(3)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(4)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(5)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(6)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(7)" tabindex="0"></span>
<span class="dot" onclick="currentSlide(8)" tabindex="0"></span>
</div>
You can check it out in Codepen.
@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 ๐
We can use
Array(5).fill()
instead ofArray(5).join(0).split(0)
๐