【发布时间】:2014-07-07 08:08:05
【问题描述】:
我有一个程序在匿名函数中使用全局变量。如果我在函数结束之前打印我的变量,它有一个值是可以的,但在函数之后它是空的。 这是我的代码,全局变量是“Mytree”,它只是一个 csv 文件的解析程序。看看最后我做了 2 打印。 我的问题是:为什么我的变量的值没有保存,如何保存。
// 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 = {} ...
【问题讨论】:
-
JavaScript 本质上是异步的,你不能仅仅因为你在文件末尾访问它就期望变量具有某种状态。尝试使用回调或承诺。
-
这里有一个很好的 JavaScript 异步模式指南(以及如何驯服它们):tech.pro/blog/1402/…
标签: javascript global-variables scope anonymous-function