Perform the same function for every item in a list / array

purpose

I have a working function (JSFiddle) . In many cases, a function is executed sequentially throughout a script. In these cases, there is a lot of repetitive code that I would like to consolidate.

Ideally change the code like this:

functionName("First_item") + 
functionName("Second_item") + 
functionName("Third_item") + 

      

Something like that:

functionName("First_item", "Second_item", "Third_item");

      

The function will be executed for each item in the list so that the result is the same, but the code is more elegant and maintainable.

Notes:

  • I don't want to use any libraries (like jQuery) to achieve the goal.

Decision

  • Amit Jokis' answer kindly pointed out that I could use arguments . When I implemented the code, the modified function (JSFiddle) only returned the string output

    for the first argument / item.

  • Vanices answers indicate a possible solution.

    • Create one line from the output of all arguments / elements by concatenating (concatenating) the lines output

      in a for loop (using +=

      ).
    • Returns the concatenated output by placing return

      outside of the for loop.

Example

Working solution (JSFiddle) .


thank

Many thanks to everyone for their time and help with this. I really appreciate it!

+3


source to share


4 answers


EDIT: Looking at your script, you have a return inside a for loop, so the function will return after the first iteration. Place the return after the input and concatenate the output with a single line.

var output = "";
for(...){
    output += description_of_object + ": " + randomly_selected_item_from_object + ".\n";
}   
// return it
return output;

      

With Javascript only:

var actions = ["shot_type","shot_height","shot_angle","framed","scene_depth"];
for (var i = 0; i < actions.length; i++){
  FunctionName(actions[i]);
}

      



With JQuery:

$.each(["shot_type","shot_height","shot_angle","framed","scene_depth"], function(index,value){
  FunctionName(value);
});

      

I haven't tested it, but it should work.

+2


source


Using Javascript Prototype OOP: you can add each function to the array itself, so that every array in your code that will automatically have each of them can be locked.

Array.prototype.each = function(callback){
    for (var i =  0; i < this.length; i++){
        callback(this[i]);
    }
}

      

Application:

myArray.each(myCoolFunction)

['something','somethingelse',somethingother'].each(myCoolFunction)

myArray.each( function (item) {
 // if your item has a method
 item.Something();
 // if you'd like to call a function on the item:
 doSomething(item);
});

      

caveats:

Since javascript is an asynchronous language that is interpreted differently in different browsers and handles primitive objects and complex objects differently in different ways, it is recommended to use the recommended use of underscore or lodash. You can also make your own, but you need to make sure that the objects passed through it will be handled by the functions properly. This can include workarounds or creating custom callbacks for different types of objects that are passed through your function each

.



For more information: Is JavaScript the default language or password?

Libraries you should seriously consider:

lodash : https://lodash.com/docs#forEach

_([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
// β†’ logs each number and returns '1,2,3'

_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
// β†’ logs each number and returns the object (property order is not guaranteed across environments)

      

Underline : http://underscorejs.org/#each

_.each([1, 2, 3], alert);
=> alerts each number in turn...

      

+5


source


You don't need an array. Just usearguments

function functionName(){
   for(var i = 0; i < arguments.length; i++){
      // do something with arguments[i];
   }
}

      

and then you can do

functionName("shot_type","shot_height","shot_angle","framed","scene_depth");

      

PS @codebox's solution works if support for older IE is not an issue. Not sure why he deleted it ... so put it here for help. His answer usingforEach

["shot_type","shot_height","shot_angle","framed","scene_depth"].forEach(FunctionName);

      

+3


source


To avoid redundancy in your code, use an array with the values ​​you want to pass through the function and call the function in a loop.

var vals=["shot_type","shot_height","shot_angle","framed","scene_depth"];
for(var i=0; i<vals.length; i++)
{
    FunctionName(vals[i]);
}

      

If you want to expand the function (by adding another parameter), you can simply extend the for-loop and array structure.

Alternatively, you can fill an object with values ​​and process that logic in the object. But it will matter when the function is called.

+2


source







All Articles