Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't make functions within a loop [duplicate]

What would be the correct way to solve the jslint error in this case? I'm adding a getter function to an object which uses this. I don't know how to do this without creating the function inside the loop.

for (var i = 0; i<processorList.length; ++i) {    result[i] = {        processor_: timestampsToDateTime(processorList[i]),        name_: processorList[i].processorName,        getLabel: function() { // TODO solve function in loop.             return this.name_;        }    }; } 
like image 459
Thijs Koerselman Avatar asked Apr 25 '12 16:04

Thijs Koerselman


People also ask

Can you put a function inside a loop?

"function" as a keyword is only used for defining functions, and cannot be used inside a loop (or inside an "if" or "switch" or other control statement.) The only kinds of functions that can be defined within loops are anonymous functions.

Can you loop a function in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.

Can you call a function in a loop?

We can even call a function inside from a loop as well. The function will be called each time the loop executes and will stop calling once the loop finishes. In this section, we see how we call a function from a loop.


1 Answers

Move the function outside the loop:

function dummy() {     return this.name_; } // Or: var dummy = function() {return this.name;}; for (var i = 0; i<processorList.length; ++i) {    result[i] = {        processor_: timestampsToDateTime(processorList[i]),        name_: processorList[i].processorName,        getLabel: dummy    }; } 

... Or just ignore the message by using the loopfunc option at the top of the file:

/*jshint loopfunc:true */ 
like image 57
Rob W Avatar answered Oct 09 '22 03:10

Rob W