I use Array.push()
inside a d3.xml
function to gather some data from a xml.
But it doesn't seem to work, my Array.length
= 0 whereas the console.log
SHOWS ME that my data are here...
You can see it from yourself in this example in which I reproduce the phenomena, and give log details :
function extractXMLdata(ficXML) {
// I want to put xml details in myObjects...
var myObjects = [];
/**
Let's say mx xml file has 6 nodes with the attributs id, name and color
I want to create 6 objects with these information
*/
d3.xml(ficXML,
function(error, documentFragment) {
/**
I created a loop to simulate the part where I gather information from the xml...
*/
for(var i=0;i<6;i++){
var singleNodeData = {}; // let's put node data in this object
singleNodeData.id = 'ID_'+i;
singleNodeData.name = 'fakename_'+Math.random();
singleNodeData.color = 'color_'+Math.random();
console.log(singleNodeData);
myObjects.push(singleNodeData) ;
if (i==5) console.log('How many objects in myObjects while I use "push"'? -> "+ myObjects.length);}
}
}
);
console.log(myObjects);
console.log("How many objects in myObjects ? -> "+ myObjects.length);
/** HERE IS THE LOG I GET
[] aspocD3XML.js (ligne 28) mmm, ok why not...
How many objects in myObjects ? -> 0 aspocD3XML.js (ligne 29) wait, WTF ?
Object { id="ID_0", name="fakename_0.04496411033170611", color="color_0.4732144810575395"} aspocD3XML.js (ligne 20)
Object { id="ID_1", name="fakename_0.07845324609294535", color="color_0.5036451388293461"} aspocD3XML.js (ligne 20)
Object { id="ID_2", name="fakename_0.7121437976123653", color="color_0.5682346193903798"} aspocD3XML.js (ligne 20)
Object { id="ID_3", name="fakename_0.9415245332085834", color="color_0.7830945674862615"} aspocD3XML.js (ligne 20)
Object { id="ID_4", name="fakename_0.051691757268447436", color="color_0.06430780013247395"} aspocD3XML.js (ligne 20)
Object { id="ID_5", name="fakename_0.3813858899007565", color="color_0.14585780574691742"} aspocD3XML.js (ligne 20)
How many objects in myObjects while I use "push" ? -> 6 aspocD3XML.js (ligne 22) That's what I'm expecting !!!
*/
}
I suspect, regarding the order in which lines appears in the console, that this is because "d3.xml" part is executted after the rest (due to xml loading). Anyway, I have no clue on how to work around this, and I HAVE TO get those objects out of extractXMLdata function (can't do all in d3.xml function)
Any Idea ?
Thanks very much...