Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- LOOPS: WHILE, FOR, FOR-IN
- While loops are less popular than for loops.
- They are more manual and work better with numbers.
- */
- var count = 0;
- while (count < 11) {
- count++; // if you will miss this part, program will crash
- } // prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. It stopped at 11.
- //For loop is good for looping forward over Array:
- var arr = [1, 2, 3, 4, 5];
- for(var i = 0; i < arr.length; i++) {/* start the loop when index is at 0;
- go as long as the index is smaller than the length of an Array (that means no more than 6 indeces);
- increment the index by 1*/
- print('index:' + i); // prints: at index: 0 is 1, at index: 1 is 2 etc.
- var element = arr[i];
- }
- function print(value) {
- console.log(value);
- }
- //To loop backwards over Array, you need to reverse the condition:
- for(var j = arr.length - 1; j > -1;j--) { /* start the loop when index (j) equals to the last
- Array's element; continue until index (j) is bigger than -1; decrement the index (j) by 1 */
- print('index:' + j) ; // at index: 4 is 5, at index: 3 is 4 etc
- var element = arr[j];
- }
- //For-in is designed for looping over Object
- var object = {
- one: 'a', //key and value pairs
- two: 'b',
- three: 'c'
- };
- for(var key in object){
- print('key:' + key); // dynamically accessing the value
- print('value ' + object[key]);// must use array for dynamic looping
- }
- print(object['two']); // prints 'b'
- object.four = 'd'; // we are adding more keys in to the Object, using dot notation
- object['five'] = 'e'; // we could add more keys with such syntax, too
- var keys = (Object.keys(object).length);
- print(keys); // prints 5 (keys), because we added extra two at the end
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement