code_junkie

JavaScript foreach Vs for

Nov 11th, 2011
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. var myArray = [{'key': 'value'}, {'key': 'value1'}];
  2.  
  3. for (var i = 0; i < myArray.length; i++)
  4.  
  5. for (var i in myArray)
  6.  
  7. for (var i = 0; i < a.length; i++)
  8. //do stuff with a[i]
  9.  
  10. for (var key in o)
  11. //do stuff with o[key]
  12.  
  13. for(name in object)
  14. {
  15. if (object.hasOwnProperty(name))
  16. {
  17. }
  18. }
  19.  
  20. $(['a','b','c']).each(function() {
  21. alert(this);
  22. });
  23. //Outputs "a" then "b" then "c"
  24.  
  25. for (var i = myArray.length-1; i >= 0; i--)
  26.  
  27. for (var i = 0; i < myArray.length; i++)
  28.  
  29. l = ''; for (m in obj) { l += m + ' => ' + obj[m] + 'n' } console.log(l);
  30.  
  31. var array = [0, 1, 2, , , 5];
  32.  
  33. for (var k in array) {
  34. // Not guaranteed by the language spec to iterate in order.
  35. alert(k); // Outputs 0, 1, 2, 5.
  36. // Behavior when loop body adds to the array is unclear.
  37. }
  38.  
  39. for (var i = 0; i < array.length; ++i) {
  40. // Iterates in order.
  41. // i is a number, not a string.
  42. alert(i); // Outputs 0, 1, 2, 3, 4, 5
  43. // Behavior when loop body modifies array is clearer.
  44. }
  45.  
  46. function foreach(o, f) {
  47. for(var i = 0; i < o.length; i++) { // simple for loop
  48. f(o[i], i); // execute a function and make the obj, objIndex available
  49. }
  50. }
  51.  
  52. foreach(o, function(obj, i) { // for each obj in o
  53. alert(obj); // obj
  54. alert(i); // obj index
  55. /*
  56. say if you were dealing with an html element may be you have a collection of divs
  57. */
  58. if(typeof obj == 'object') {
  59. obj.style.marginLeft = '20px';
  60. }
  61. });
  62.  
  63. for( var i=0,j=null; j=array[i++]; foo(j) );
Add Comment
Please, Sign In to add comment