I have a program where I use a global variable in an anonymous function. If I print my variable before the end of the function it is ok it has a value, but after the function it is empty. This is my code, the global variable is "Mytree", it is just a parsin program of a csv file. Look at the end I do the 2 print. My question is : why the value of my variable is not saved, and how to save it.
// My program :
var Mytree = {}; // My global variable.
d3.csv("data.csv", function (data) { // The anonymous function to parse the csv file
/* -- Parsing du csv -- */
var dataTab = [];
var j = 0;
var exigence = "";
var root = "Systeme";
for (var i = 0; i < data.length; i++) {
if (data[i].Contrat !== "") {
if (data[i].ExigenceContractuelle.split(".").length !== 1) {
exigence = data[i].ExigenceContractuelle.split(".")[0];
if (exigence.split("_").length !== 1) {
exigence = exigence.split("_")[0];
}
} else if (data[i].ExigenceContractuelle.split("-").length !== 1) {
exigence = data[i].ExigenceContractuelle.split("-")[0];
} else if (data[i].ExigenceContractuelle.split("_").lenght !== 1) {
exigence = data[i].ExigenceContractuelle.split("_")[0];
} else {
exigence = data[i].ExigenceContractuelle.split(".")[0];
}
dataTab[j] = {
name: data[i].ExigenceSystème,
textExig: data[i].TexteExigence,
validation: data[i].Validation,
discution: data[i].Discution,
SSSExig: data[i].LibelleTexte,
team: root + "/" + exigence + "/" + data[i].ExigenceContractuelle
};
j++;
}
}
/* -- -- */
/* -- Tableau -> Json Tree -- */
function fillTree(name, textExigTmp, SSSExigTmp, validation, discution, steps) {
var current = null,
existing = null,
i = 0;
for (var y = 0; y < steps.length; y++) {
if (y === 0) {
if (!Mytree.children || typeof Mytree.children === 'undefined') {
Mytree = {
text: steps[y],
textExig: textExigTmp,
SSSExig: SSSExigTmp,
leaf: false,
children: [],
open: false,
discution: discution == "" ? 0 : discution,
validation: validation == 1 ? true : false
};
}
current = Mytree.children;
} else {
existing = null;
for (i = 0; i < current.length; i++) {
if (current[i].text === steps[y]) {
existing = current[i];
break;
}
}
if (existing) {
current = existing.children;
} else {
current.push({
text: steps[y],
textExig: textExigTmp,
SSSExig: SSSExigTmp,
leaf: false,
children: [],
open: false,
discution: discution == "" ? 0 : discution,
validation: validation == 1 ? true : false
});
current = current[current.length - 1].children;
}
}
}
current.push({
text: name,
textExig: textExigTmp,
SSSExig: SSSExigTmp,
leaf: true,
open: false,
discution: discution == "" ? 0 : discution,
validation: validation == 1 ? true : false
});
}
for (x = 0; x < dataTab.length; x++) {
steps = dataTab[x].team.split('/');
fillTree(dataTab[x].name, dataTab[x].textExig, dataTab[x].SSSExig, dataTab[x].validation, dataTab[x].discution, steps);
}
/* -- -- */
console.log(window.Mytree); // It's ok Mytree is not empty
});
console.log(window.Mytree); // Mytree = {} ...