【发布时间】:2017-04-17 18:04:11
【问题描述】:
披露:我是新手,对 JS 缺乏经验,但我花了几个小时试图通过 Stackoverflow 和其他互联网资源找到解决方案。我的导师这周不在,所以我希望这里的人能够帮助我。提前谢谢!
简介:我正在尝试通过变量 setupTotal 跟踪运行总计。我将它放在函数 getStoredData 的顶部,认为它会像一个全局函数一样在 getStoredData 中的 for 循环期间被覆盖或重置。我已经包含了上下文的周围代码,并将我认为与我遇到的实际问题相关的内容加粗。
问题: 每次 for 循环通过迭代循环时,我的 setupTotal 变量都会被重置。我在控制台日志和 buildSetup 函数末尾的 setupFees.innerHTML 中都看到了这一点。据我了解,当我指定 var setupTotal = 0;在 getStoredData 函数的开头,我在 buildSetup 嵌套函数中所做的更新应该覆盖原始值。然而,每次运行新的迭代时,setupTotal 值又从 0 开始。
function getStoredData() {
// Builds "Service Row" div to house the incoming content
buildDivRow();
var setupTotal = 0;
// Loops through the boxes to see what's stored
for (var service in serviceDatabase) {
for (id=0; id < serviceDatabase[service].length; id++) {
console.log("Starting " + service + ": " + serviceDatabase[service][id]);
// Get the stored data if it exists
var inputID = service + "-input-" + id;
var getData = localStorage.getItem(inputID);
console.log("Attempting data retrieval for " + inputID + ": " + getData);
// Passes the info to a function that creates the HTML to display stored data
if (getData != null) {
// Passes the info to functions that captures "total" data
console.log("buildSetup starting, service: " + service);
console.log("buildSetup starting, getData: " + getData);
console.log("buildSetup starting, setupTotal): " + setupTotal);
buildSetup(service, getData, setupTotal);
// Passes the info to a function that builds the div containers
buildDivXs12(getData, inputID, service, id);
// Logs that the data was found successfully or not
console.log("Retrieved ID (" + inputID + ") and data (" + getData + ")");
} else {
console.log("No data to retrieve for " + serviceDatabase[service][id] + ": " + inputID );
}
}
}
}
// Keeps track of the setup fees
function buildSetup(service, getData, setupTotal) {
// Retrieve the setup fee
var setup = setupDatabase[service][getData];
console.log("buildSetup ending, setup: " + setup);
// Update the setupTotal global var
setupTotal = parseInt(setupTotal) + parseInt(setup);
console.log("buildSetup ending, setupTotal): " + setupTotal);
// Update the setupFees inner HTML
var setupFees = document.getElementById("setupFee");
setupFees.innerHTML = setupTotal;
}
【问题讨论】:
-
你的代码中真的有 ** 吗?它不会对您产生任何错误吗?
-
@ChristianEsperar 那是 bold 效果(因为它是一个代码 sn-pt
**不会被降价处理)! -
setupTotal不是全球性的!仅在getStoredData范围内可见。 -
如果没有您正在使用的数据(在它的适当结构中),就无法回答这个问题。
setupTotal是从setup计算出来的,而setup又是从一个名为setupDatabase的对象的属性中计算出来的。我们对其中任何一个都没有价值。
标签: javascript