Created
July 28, 2013 18:33
-
-
Save raineorshine/6099565 to your computer and use it in GitHub Desktop.
Basic array operations.
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
| /* ARRAYS */ | |
| var fruit = ["pineapple", "mango", "limón"]; // array literal (i.e. creating a new array by typing in the values directly) | |
| var empty = []; // an array with no items | |
| // accessing an array | |
| console.log( fruit[0] ); // print out 'pineapple' | |
| console.log( fruit[1] ); // print out 'mango' | |
| var myfruit = fruit[1]; | |
| console.log( myfruit ); // print out 'mango' | |
| // push: add an item to an array | |
| fruit.push("guanábana"); // now fruit looks like this: ["pineapple", "mango", "limón", "guanábana"] | |
| // pop: remove the last item from the array | |
| console.log( fruit.pop() ); // print out 'guanábana'. AND now fruit looks like this: ["pineapple", "mango", "limón"] | |
| // get the length of an array | |
| console.log( fruit.length ); // print out 3 | |
| // you can also use the length property within if statements | |
| if(fruit.length > 10) { | |
| console.log("You have a ton of fruit!"); | |
| } | |
| // standard for loop (how to loop through an array) | |
| // THREE PARTS: | |
| // 1. INITIALIZER: var i=0; (i.e. what the loop variable starts at) | |
| // 2. CONDITION: i<fruit.length; (i.e. when the loop should stop running) | |
| // 3. ITERATOR: i++ (i.e. how to advance the loop variable each iteration) | |
| // If you're looping through any array, the only thing that changes, is the array variable in the CONDITION | |
| for(var i=0; i<fruit.length; i++) { | |
| console.log("Current fruit is: " + fruit[i]); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment