Search code examples
javascriptarraysfor-looparrow-functions

Can I use a for loop iterator in the parameter of an arrow function to be passed into the loop?


I am programming a physics simulation, and the current version is on my website. I don't know if I can post the link, so I won't. The program is a multi-link inverted pendulum, and I am trying to write functions for running the physics. To do this, I have to set a lot of arrays for the different values of each inverted pendulum, such as an array for all of the moment-of-intertias, the masses, the thetas, and more. This is how I am doing it right now:

    function fillArray(begin, end, alg) {
        let arr = [];

        for (let i = begin; i < end; i++) {
            arr[i] = alg();
        }
        return arr;
    }

    let Ls = fillArray(0, numPoles, () => 2 * this.ls[i]);

When I output the Ls array, it says that every element within is Nan (not a number). What am I doing wrong? How can I make this work?


Solution

    1. the alg() function is passed outside the loop where contains a variable i.
      this.ls[i] is undefined where i is undefined
      so 2 * undefined return NaN

    2. this.ls is not in the function scope so the arrow function should use global ls or you have to pass it into the function.

    3. Try the following code

    function fillArray(begin, end, alg) {
    	let arr = [];
    	for (let i = begin; i < end; i++) {
    		arr[i] = alg(i);
    	}
    	return arr;
    }
    let ls = [1,3,11,22];
    let numPoles = 3;
    let Ls = fillArray(0, numPoles, (i) => 2 * ls[i]);
    console.log(Ls);