Skip to content Skip to sidebar Skip to footer

Programmatically Setting Third Statement Of For Loop

Wondering if there is by any chance to programmatically setting third statement of forloop var conditionProgrammatically = 'i++';//or 'x--' for (var i = 0; i < 10; conditionPro

Solution 1:

You can use any expression you want there including calling a function. You just need to be careful of scope. So, for example, this works:

varconditionProgramatically = () => i++ ;

for (var i = 0; i < 10; conditionProgramatically()) {
  console.log(i)
}

But it depends on the fact that var i is in a scope shared by the function. This, however, doesn't work:

varconditionProgramatically = () => i++ ;

for (let i = 0; i < 10; conditionProgramatically()) {
  console.log(i)
}

Because let is scoped to the block and not available.

Of course you can share an object which is mutable by passing it as an argument like:

fn = (o) => o.i += 1for (let o = {i:0}; o.i < 10; fn(o)) {
    console.log(o.i)
  }
  

This allows you to use let, but is a little hard on the eyes.

All said, it's probably going to be easier to make your logic fit in a simple expression rather than calling a function. You can still perform some logic, though:

for (let i = 0; Math.abs(i) < 10; i = Math.random() > .65  ? i -1: i + 1) {
  console.log(i)
}

Solution 2:

Usually, in functional programmings (like python and javascript), we can use dictionary (or objects) to store functions.

var myFunctions = {
  "a": function (i) { return i + 1 },
  "b": function (i) { return i - 3 }
};

Then, we can set the condition as the key to the dictionary:

myCondition = "a"; // this will set condition to increment by 1

Here is your for loop:

for (i = 0; i < n; i = myFunctions[myCondition](i)) {
  // whatever
}

Post a Comment for "Programmatically Setting Third Statement Of For Loop"