-
-
Save AleeRojas/0259b82f3d1507a38ef5683f29efcd31 to your computer and use it in GitHub Desktop.
Template Literals example: for each
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Template literals forEach example | |
Using Array.map(), we can create a forEach within template literals. | |
*/ | |
var items = [ | |
{ name: 'Teddy' }, | |
{ name: 'Dolores' }, | |
{ name: 'William' }, | |
{ name: 'Bernard' } | |
] | |
element = document.createElement('div') | |
element.innerHTML = ` | |
<h1>This element has items</h1> | |
${this._items.map((item, i) => ` | |
<div> | |
I am item number ${i < 10 ? '0' + (i + 1) : i + 1}. | |
My name is ${item.name}. | |
</div> | |
`.trim()).join('')} | |
` | |
/* | |
Results: | |
<div> | |
<h1>This element has items</h1> | |
<div>I am item number 01. My name is Teddy.</div> | |
<div>I am item number 02. My name is Dolores.</div> | |
<div>I am item number 03. My name is William.</div> | |
<div>I am item number 04. My name is Bernard.</div> | |
</div> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment