披露:我是一个相当新的,没有经验的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;
}
答案 0 :(得分:0)
根据您的代码,您可以做的是返回 buildSetup 函数上的 setupTotal 值,然后在 getStoredData 上调用后再分配它功能如下:
function getStoredData() {
..
console.log("buildSetup starting, setupTotal): " + setupTotal);
setupTotal = buildSetup(service, getData, setupTotal);
..
}
function buildSetup(service, getData, setupTotal) {
..
setupFees.innerHTML = setupTotal;
return setupTotal;
}