Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.03 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. In Javascript, how to execute a function on elements of two seqs concurently?
  2. var a = [1, 2, 3];
  3. var b = [11, 12, 13];
  4. function my_func() { /* some custom function */}
  5.        
  6. my_func(1,11);
  7. my_func(2,12);
  8. my_func(3,13);
  9.        
  10. _.each( _.zip(a,b), my_func );
  11.  
  12. function my_func( pair ){
  13.   alert( pair[0] + pair[1] );
  14. }
  15.        
  16. _.each( _.zip(a,b), function( pair ){
  17.   my_func( pair[0], pair[1] );
  18.   // or: my_func.apply( null, pair );
  19. });
  20.  
  21. function my_func( a, b ){
  22.   alert( a + b );
  23. }
  24.        
  25. function wrapply( func, thisObj ){
  26.   return function( args ){
  27.     return func.apply( thisObj, args );
  28.   }
  29. }
  30.  
  31. var add = wrapply( function(a,b){ return a+b; });
  32. alert( add([1,2]) );
  33.        
  34. for (var i = 0; i < a.length; i++) {
  35.     my_func(a[i], b[i]);
  36. }
  37.        
  38. $.each(a, function(i, aItem) { my_func(aItem, b[i]); });
  39.        
  40. $.zip(a, b).each(function() {
  41.     var aItem = this[0];
  42.     var bItem = this[1];
  43.     my_func(aItem, bItem);
  44. });
  45.        
  46. [1,2,3].forEach(function(e, i, arr){my_func(e, arr[i]);}, [11,12,13]);
  47.        
  48. $.each(a, function(index, value) {
  49.     my_func(value, b[index]);
  50. });