-1

I have a simple iteration using jQuery each

 $.each(data.Limit, function (index, value) {
   alert(value.LimitCategory);
 });

How do I change this to call an actual javascript function - which I want to maintain separately from the loop?

e.g.

function DoSomethingElse(index, value){
//more things here
};

I've tried a few ways and can't seem to get the syntax.

BlueChippy
  • 5,935
  • 16
  • 81
  • 131
  • 8
    `$.each(data.Limit, DoSomethingElse)` – p.s.w.g Dec 15 '14 at 04:25
  • 1
    just pass the function reference(function name) as the second param – Arun P Johny Dec 15 '14 at 04:25
  • 1
    maybe read an article on mdn about JavaScript too – Shiala Dec 15 '14 at 04:28
  • possible duplicate of http://stackoverflow.com/questions/13286233/javascript-pass-function-as-parameter – JLRishe Dec 15 '14 at 06:38
  • @JLRishe not exactly a duplicate. However, both questions lack basic understanding of how JS callback functions work, or how JS functions behave in a first-class language like javascript where function are just variables with a type of function allowing them to be used as a function arguments and bla bla – Shiala Dec 11 '15 at 18:38

3 Answers3

2

Just pass the function as the second param of your each method:

$.each(data.Limit, DoSomethingElse)
ianaya89
  • 4,153
  • 3
  • 26
  • 34
0

Simply declare the needed method and call it.

 $.each(data.Limit, function (index, value) {
   someMethod(index, value);
 });

 function someMethod(i, v){
   // process
 }
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
0

So when you pass in an anonymous function as the second parameter of $.each you ARE ACTUALLY CALLING AN actual JAVASCRIPT FUNCTION (sorry about the caps my phone is not behaving well.) in case you wanna define the function and pass in a function name, the syntax would be as follows.

function myFunction (i, val) {
    //i is for index
    //use this or val for current object in array
}

$.each(array, myFunction);
Shiala
  • 486
  • 3
  • 8