Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. /*
  2. LOOPS: WHILE, FOR, FOR-IN
  3. While loops are less popular than for loops.
  4. They are more manual and work better with numbers.
  5. */
  6.  
  7. var count = 0;
  8. while (count < 11) {
  9. count++; // if you will miss this part, program will crash
  10. } // prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. It stopped at 11.
  11.  
  12. //For loop is good for looping forward over Array:
  13.  
  14. var arr = [1, 2, 3, 4, 5];
  15. for(var i = 0; i < arr.length; i++) {/* start the loop when index is at 0;
  16. go as long as the index is smaller than the length of an Array (that means no more than 6 indeces);
  17. increment the index by 1*/
  18. print('index:' + i); // prints: at index: 0 is 1, at index: 1 is 2 etc.
  19. var element = arr[i];
  20. }
  21.  
  22. function print(value) {
  23. console.log(value);
  24. }
  25. //To loop backwards over Array, you need to reverse the condition:
  26.  
  27. for(var j = arr.length - 1; j > -1;j--) { /* start the loop when index (j) equals to the last
  28. Array's element; continue until index (j) is bigger than -1; decrement the index (j) by 1 */
  29. print('index:' + j) ; // at index: 4 is 5, at index: 3 is 4 etc
  30. var element = arr[j];
  31. }
  32.  
  33. //For-in is designed for looping over Object
  34.  
  35. var object = {
  36. one: 'a', //key and value pairs
  37. two: 'b',
  38. three: 'c'
  39. };
  40.  
  41. for(var key in object){
  42. print('key:' + key); // dynamically accessing the value
  43. print('value ' + object[key]);// must use array for dynamic looping
  44. }
  45.  
  46. print(object['two']); // prints 'b'
  47. object.four = 'd'; // we are adding more keys in to the Object, using dot notation
  48. object['five'] = 'e'; // we could add more keys with such syntax, too
  49.  
  50. var keys = (Object.keys(object).length);
  51. print(keys); // prints 5 (keys), because we added extra two at the end
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement