Question

Here is a simplified version of something I'm trying to run:

for ( winDoorNo = 0; winDoorNo < aWinDoorSetSpec.no_of_winDoors; winDoorNo ++ ) {
    (function (winDoorNo, self) {

        self.tangentVectors_azimuth = [];
        self.tangentVectors_polar   = [];

        self.tangentVectors_azimuth[winDoorNo] = tangentPlane.tangentVector_azimuth;
        self.tangentVectors_polar[winDoorNo]   = tangentPlane.tangentVector_polar;

    })(winDoorNo, this);
}

but I'm finding that the self.tangentVectors_azimuth array only contains a value on the last value that the for loop index variable had. I found this post describing a similar problem and I implemented the suggested solution which is to use a closure. However this does not work for me. After the for loop has executed, the value of this.tangentVectors_azimuth is still:

[undefined, undefined, Object { x=0.01999999996662183, y=0.01599999957331022, z=0, more...}]
Was it helpful?

Solution

You are creating new arrays for each iteration in the loop, so each time you will throw away the previous result.

Create the arrays outside the loop:

this.tangentVectors_azimuth = [];
this.tangentVectors_polar = [];
for (winDoorNo = 0; winDoorNo < aWinDoorSetSpec.no_of_winDoors; winDoorNo++) {
  this.tangentVectors_azimuth[winDoorNo] = tangentPlane.tangentVector_azimuth;
  this.tangentVectors_polar[winDoorNo] = tangentPlane.tangentVector_polar;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top