1

I would like to use an array of functions ins in a jquery each loop and pass parameters to sad functions.

Something like what is below.

var test = function(x) { return x+1;};
var test2 = function (x) { return x+2};
var mark = [test,test2]; 

mark.each(function() { $(this)(3)});

expected result
4
5

how do I achieve this.

Working example of answer

var test = function(x) { return x+1;};
var test2 = function (x) { return x+2;};
var mark = [test,test2]; $.each(mark, function () {
  console.log(  this(3));
});

2 Answers 2

4

Did you try this(3)

$.each(mark, function () {
    this(3);
});

also note, you need $.each to iterate and array not mark.each as .each is available only on jQuery object.

Sign up to request clarification or add additional context in comments.

2 Comments

@Archer it works for me. I have updated my question to reflect it
How bizarre. I did it in the console on this page and it returned the functions as object references. When I did it in jsfiddle it worked. Oh well! +1 :)
1

you would need to put your array as the first parameter of your $.each() method

there are 2 different types of jQuery each() methods

the first iterates over both objects and arrays:

http://api.jquery.com/jQuery.each/

// array
$.each([ 52, 97 ], function( index, value ) {
   alert( index + ": " + value );
});

// object
var obj = {
      "flammable": "inflammable",
      "duh": "no duh"
};
$.each( obj, function( key, value ) {
      alert( key + ": " + value );
});

the second iterates over a collection of elements

http://api.jquery.com/each/

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>

selector each look like this

// collection of elements
$("li").each(function( index ) {
     console.log( index + ": " + $( this ).text() );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.