Last active
January 8, 2017 03:52
-
-
Save marklearst/de5fc69efff14e9c9c0041898f817849 to your computer and use it in GitHub Desktop.
forEach example 1
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
| // Object with div element and base attributes | |
| var divElementObj = { | |
| tag: 'div', | |
| class: 'col-4' | |
| } | |
| // An Array of Fruits | |
| var fruits = [ | |
| 'apple', | |
| 'pear', | |
| 'fig' | |
| ] | |
| // Logging fruits before forEach is called | |
| console.log( fruits ); | |
| console.log( '\n' ); | |
| //----------------------------------------- | |
| // Utility function that wraps text with a <div> | |
| // function divWrapper( element, index, arr ) { | |
| // array[index] = '<' + this.tag + '>' | |
| // array[index] += element | |
| // array[index] += '</' + this.tag + '>' | |
| // ES6 Template Literal | |
| // array[index] = `<${this.tag} class="${this.class}">${element}</${this.tag}>`; | |
| // } | |
| // Call forEach with and pass in thisDiv as Argument | |
| // fruits.forEach( divWrapper, divElementObj ) | |
| //----------------------------------------- | |
| // Passing in an anonymous function as first argument | |
| fruits.forEach( function( element, index, array ) { | |
| array[index] = '<' + this.tag + '>' | |
| array[index] += element | |
| array[index] += '</' + this.tag + '>' | |
| // ES6 Template Literal | |
| // return `<${this.tag} class="${this.class}">${element}</${this.tag}>`; | |
| }, divElementObj ) | |
| // After forEach was called on fruits Array. | |
| console.log( newFruits ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment