sarah sarah - 4 months ago 8
Javascript Question

How to call items from an array inside a function

I have a function "zoom" which takes the following format:

zoom( [a,b,c,d....], [a,b,c,d...] );


I also have a for loop which gets me the values that need to go into the zoom array:

ABC.getAggregation("V")[0].getItems().forEach( function (item) {
var a = item.getPosition().split(";")[0];
var b = item.getPosition().split(";")[1];
ABC.zoom( [...], [...] );
});


How can I add variables a and b into the arrays of function zoom?

All variable a's must go into the first array and all variables b must go into the second.

Example:

ABC.getAggregation("V")[0].getItems()
//returns a list of 3 objects
item.getPosition()
//returns e.g "0,0,0" for the first item and so on (for all 3)
item.getPosition().split(";")[0] = "0"
//now i want to add this to the zoom function.

var a = item.getPosition().split(";")[0];
//this produces three string values "14.5". "4", "8.64"


var b = item.getPosition().split(";")[1];
//this produces three string values "5.7","6.8","1"


Now, I want to put these string values into zoom like this:

ABC.zoom( [14.5. 4, 8.64], [5.7,6.8,1] );
//note - they're not strings anymore.


How can I achieve this result?

Answer

You cannot execute the call to ABC.zoom() inside the .forEach() loop, since you'll only get the whole data set once all iterations have been executed.

I think you need something along those lines:

var zoomA = [],
    zoomB = [];

ABC.getAggregation("V")[0].getItems().forEach( function (item) {
  var a = item.getPosition().split(";")[0];
  var b = item.getPosition().split(";")[1];
  zoomA.push(Number(a));
  zoomB.push(Number(b));
});

ABC.zoom(zoomA, zoomB);

Please let me know if I somehow misunderstood what you are trying to do.