Last active
March 9, 2016 21:45
-
-
Save csdear/5a8cad1e4d2ab481fd27 to your computer and use it in GitHub Desktop.
.each jQuery function iterates through an array or an object
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
| //consolable | |
| //1. Simple usage, on an array | |
| // basically pass in an array, .each will iterate over each element in the array. | |
| // here the output is the index (0,1,3), then the value ( 52, 97 ) | |
| //This can get more sophisticated when passing in data from a Json file. | |
| $.each([ 52, 97 ], function( index, value ) { | |
| alert( index + ": " + value ); | |
| }); | |
| //2. If an object is passed in instead of an array, the callback passed a key-value pair each time. | |
| //see jsbin https://jsbin.com/rekufa/2 | |
| var robotWeakness = { | |
| "water": "Will Rust", | |
| "flame": "internal circuitry damage", | |
| "electricity" : "Stun damage" | |
| }; | |
| $.each(robotWeakness, function( key, value ) { | |
| document.write( key + ": " + value + "</br>" ); | |
| }); | |
| //3. How to break out of the iteration. return once a certain value is hit. | |
| var robotWeakness = { | |
| "water": "Will Rust", | |
| "flame": "internal circuitry damage", | |
| "emotion" : "Sympathy", | |
| "electricity" : "Stun damage" | |
| }; | |
| $.each(robotWeakness, function( key, value ) { | |
| document.write( key + ": " + value + "</br>" ); | |
| //break the iteration if you hit this... | |
| return ( value !== "Sympathy"); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment