
在JavaScript中,当我们需要从外部资源(如JSON文件)加载数据时,通常会涉及异步操作。fetch API就是典型的异步函数,它会立即返回一个Promise对象,而不是等待数据完全加载后再返回实际值。这意味着,如果我们在fetch操作完成之前尝试访问其内部定义的数据,就会遇到变量未定义的问题。
原始代码中,fetchFirstItemFromJSON 是一个异步函数,它在内部定义了 firstItem 变量。然而,在函数外部,buttons 数组的初始化是同步进行的,它试图立即使用 firstItem。由于 fetchFirstItemFromJSON 的异步特性,当 buttons 数组被创建时,firstItem 尚未被赋值,导致 firstItem 为 undefined,从而引发错误。
原始代码中的问题点:
async function fetchFirstItemFromJSON(filePath) {
// ... 异步获取数据并赋值给 firstItem
const firstItem = data[0];
console.log(firstItem); // 此时 firstItem 才有值
}
fetchFirstItemFromJSON('path/to/your/file.json'); // 这是一个异步调用
// 紧接着这里,firstItem 仍然是 undefined,因为上面的异步函数还未执行完毕
const buttons = [{
htmlFile: 'interactive_2.html',
pngFile: 'fctime_2.png',
time: firstItem, // 错误发生在这里,firstItem 尚未被定义
},
// ... 其他按钮数据
];为了正确地在异步操作完成后获取并使用数据,我们需要确保在数据可用之后再执行依赖于这些数据的代码。JavaScript 的 async/await 语法是解决此问题的优雅方式。
立即学习“Java免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
首先,我们需要修改 fetchFirstItemFromJSON 函数,使其在成功获取数据后,将所需的数据项作为其Promise的解决值返回。
async function fetchFirstItemFromJSON(filePath) {
try {
// 注意:在浏览器环境中,fetch 无法直接访问本地文件系统路径(如 C:\Users\...)。
// JSON文件需要通过HTTP(S)服务提供,或使用相对/绝对URL。
// 如果在开发阶段,可以使用Live Server等工具启动本地服务器。
const response = await fetch(filePath); // 异步获取JSON文件
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // 解析JSON数据
// 返回列表中的第一个数据项
return data[0];
} catch (error) {
console.error('Error reading JSON file:', error);
return null; // 发生错误时返回 null 或抛出错误
}
}接下来,我们需要在 DOMContentLoaded 事件监听器内部,使用 await 关键字等待 fetchFirstItemFromJSON 函数返回结果。由于 await 只能在 async 函数中使用,因此 DOMContentLoaded 的回调函数也需要声明为 async。
document.addEventListener("DOMContentLoaded", async function () { // 将回调函数声明为 async
let firstItem = null; // 声明 firstItem 变量
// 假设 'assets/times.json' 是一个可通过HTTP(S)访问的相对路径
// 替换为实际的JSON文件路径
const jsonFilePath = './assets/times.json';
// 等待 fetchFirstItemFromJSON 完成并返回数据
firstItem = await fetchFirstItemFromJSON(jsonFilePath);
if (firstItem === null) {
console.error("Failed to load first item from JSON. Using a fallback or default value.");
firstItem = "默认时间"; // 提供一个备用值以防加载失败
}
// 现在 firstItem 已经包含了从JSON文件获取到的第一个数据项
// 可以在这里安全地使用它来初始化 buttons 数组
const buttons = [{
htmlFile: 'interactive_2.html',
pngFile: 'fctime_2.png',
time: firstItem, // firstItem 现在有正确的值
},
{
htmlFile: 'interactive_4.html',
pngFile: 'fctime_4.png',
time: "20/05\n20:00",
},
// ... 其他按钮数据
];
// 后续的按钮创建、事件监听等逻辑保持不变
const buttonContainer = document.getElementById("buttonContainer");
const mapDetails = document.getElementById("mapDetails");
const mapDisplay = document.getElementById("mapDisplay");
const mapRange = document.getElementById("mapRange");
const previousButton = document.getElementById("previousButton");
const nextButton = document.getElementById("nextButton");
let activeButtonIndex = 0;
mapRange.max = buttons.length - 1;
function setActiveButton(index) {
const buttonsElements = buttonContainer.getElementsByClassName("mapButton");
for (let i = 0; i < buttonsElements.length; i++) {
buttonsElements[i].classList.remove("activeMapButton");
}
buttonsElements[index].classList.add("activeMapButton");
activeButtonIndex = index;
}
function changeMap(button) {
mapDetails.src = `./assets/${button.pngFile}`;
mapDisplay.src = `./assets/${button.htmlFile}`;
}
function handleButtonClick(index) {
if (index != +activeButtonIndex) {
setActiveButton(index);
changeMap(buttons[index]);
mapRange.value = index;
}
}
function handlePreviousButtonClick() {
if (activeButtonIndex > 0) {
handleButtonClick(+activeButtonIndex - 1);
}
}
function handleNextButtonClick() {
if (+activeButtonIndex < buttons.length - 1) {
handleButtonClick(+activeButtonIndex + 1);
}
// 注意:这里需要确保 buttons 数组已被正确初始化
// 如果 buttons 在异步加载前被初始化,可能会导致长度错误
}
buttons.forEach((button, index) => {
const buttonElement = document.createElement("button");
const prevNextButtons = document.querySelector(".nextprev");
buttonElement.innerHTML = `${button.time.replace(/\n/g, "<br>")}`;
buttonElement.classList.add("mapButton");
buttonElement.addEventListener("click", () => handleButtonClick(index));
buttonContainer.insertBefore(buttonElement, prevNextButtons);
});
previousButton.addEventListener("click", handlePreviousButtonClick);
nextButton.addEventListener("click", handleNextButtonClick);
mapRange.addEventListener("input", () => {
handleButtonClick(mapRange.value);
});
setActiveButton(activeButtonIndex);
changeMap(buttons[activeButtonIndex]);
});
// 其他独立的功能(如更新侧边栏内容)可以继续在 DOMContentLoaded 外部或内部独立执行
// updateSidebarContent('./assets/information.md', 'informationContent');
// updateSidebarContent('./assets/extended_outlook.md', 'extendedOutlookContent');下面是整合了上述修改后的完整JavaScript代码结构,展示了如何正确地从JSON文件异步加载数据并将其应用于页面元素:
// 异步函数:从指定路径获取JSON文件的第一个数据项
async function fetchFirstItemFromJSON(filePath) {
try {
// 浏览器中的 fetch API 无法直接访问本地文件系统路径(如 C:\Users\...)。
// 请确保 filePath 是一个可以通过 HTTP(S) 访问的 URL(相对或绝对)。
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data[0]; // 返回JSON数组的第一个元素
} catch (error) {
console.error('Error reading JSON file:', error);
return null; // 发生错误时返回 null
}
}
// DOM 内容加载完毕后执行主逻辑
document.addEventListener("DOMContentLoaded", async function () {
let firstItemValue = null; // 用于存储从JSON获取的第一个数据项
// 定义JSON文件的路径。请确保这个路径是服务器可访问的。
const jsonFilePath = './assets/times.json';
// 异步等待 JSON 数据的加载
firstItemValue = await fetchFirstItemFromJSON(jsonFilePath);
// 如果加载失败,可以使用一个默认值或进行错误处理
if (firstItemValue === null) {
console.warn("未能从JSON文件加载第一个数据项,使用默认值。");
firstItemValue = "未知时间"; // 设置一个默认值以防止后续代码出错
}
// 定义按钮数据数组,现在可以安全地使用 firstItemValue
const buttons = [{
htmlFile: 'interactive_2.html',
pngFile: 'fctime_2.png',
time: firstItemValue, // 使用从JSON获取的值
},
{
htmlFile: 'interactive_4.html',
pngFile: 'fctime_4.png',
time: "May 28\n06 PM ET",
},
{
htmlFile: 'interactive_6.html',
pngFile: 'fctime_6.png',
time: "May 28\n08 PM ET",
},
{
htmlFile: 'interactive_8.html',
pngFile: 'fctime_8.png',
time: "May 28\n10 PM ET",
},
{
htmlFile: 'interactive_10.html',
pngFile: 'fctime_10.png',
time: "May 29\n12 AM ET",
},
{
htmlFile: 'interactive_12.html',
pngFile: 'fctime_12.png',
time: "May 29\n02 AM ET",
},
{
htmlFile: 'interactive_14.html',
pngFile: 'fctime_14.png',
time: "May 29\n06 AM ET",
},
{
htmlFile: 'interactive_16.html',
pngFile: 'fctime_8.png',
time: "May 29\n08 AM ET",
},
{
htmlFile: 'interactive_18.html',
pngFile: 'fctime_10.png',
time: "May 29\n10 AM ET",
},
{
htmlFile: 'interactive_24.html',
pngFile: 'fctime_12.png',
time: "May 29\n12 PM ET",
},
{
htmlFile: 'interactive_28.html',
pngFile: 'fctime_14.png',
time: "May 29\n02 PM ET",
},
{
htmlFile: 'interactive_32.html',
pngFile: 'fctime_16.png',
time: "May 29\n06 PM ET",
},
{
htmlFile: 'interactive_36.html',
pngFile: 'fctime_18.png',
time: "May 29\n10 PM ET",
},
{
htmlFile: 'interactive_40.html',
pngFile: 'fctime_24.png',
time: "May 30\n12 AM ET",
},
];
// 获取DOM元素
const buttonContainer = document.getElementById("buttonContainer");
const mapDetails = document.getElementById("mapDetails");
const mapDisplay = document.getElementById("mapDisplay");
const mapRange = document.getElementById("mapRange");
const previousButton = document.getElementById("previousButton");
const nextButton = document.getElementById("nextButton");
let activeButtonIndex = 0;
// 设置范围滑块的最大值
mapRange.max = buttons.length - 1;
// 辅助函数:设置当前活跃按钮的样式
function setActiveButton(index) {
const buttonsElements = buttonContainer.getElementsByClassName("mapButton");
for (let i = 0; i < buttonsElements.length; i++) {
buttonsElements[i].classList.remove("activeMapButton");
}
if (buttonsElements[index]) { // 确保索引有效
buttonsElements[index].classList.add("activeMapButton");
}
activeButtonIndex = index;
}
// 辅助函数:更新地图详情和显示
function changeMap(button) {
mapDetails.src = `./assets/${button.pngFile}`;
mapDisplay.src = `./assets/${button.htmlFile}`;
}
// 处理按钮点击事件
function handleButtonClick(index) {
if (index !== +activeButtonIndex) {
setActiveButton(index);
changeMap(buttons[index]);
mapRange.value = index;
}
}
// 处理“上一个”按钮点击事件
function handlePreviousButtonClick() {
if (activeButtonIndex > 0) {
handleButtonClick(+activeButtonIndex - 1);
}
}
// 处理“下一个”按钮点击事件
function handleNextButtonClick() {
if (+activeButtonIndex < buttons.length - 1) {
handleButtonClick(+activeButtonIndex + 1);
}
}
// 根据按钮数据数组创建按钮元素并添加到DOM
buttons.forEach((button, index) => {
const buttonElement = document.createElement("button");
const prevNextButtons = document.querySelector(".nextprev"); // 假设这个元素存在
buttonElement.innerHTML = `${button.time.replace(/\n/g, "<br>")}`;
buttonElement.classList.add("mapButton");
buttonElement.addEventListener("click", () => handleButtonClick(index));
buttonContainer.insertBefore(buttonElement, prevNextButtons);
});
// 为导航按钮添加事件监听器
previousButton.addEventListener("click", handlePreviousButtonClick);
nextButton.addEventListener("click", handleNextButtonClick);
// 为范围滑块添加事件监听器
mapRange.addEventListener("input", () => {
handleButtonClick(parseInt(mapRange.value, 10));
});
// 初始化设置:设置初始活跃按钮和地图显示
setActiveButton(activeButtonIndex);
changeMap(buttons[activeButtonIndex]);
});
// 独立功能:更新侧边栏内容
// 确保这些函数和它们引用的文件路径是正确的
// function updateSidebarContent(markdownFile, targetElementId) {
// fetch(markdownFile)
// .then(response => response.text())
// .then(markdown => {
// // 假设你有一个Markdown解析库,例如 marked.js
// // document.getElementById(targetElementId).innerHTML = marked(markdown);
// // 如果没有解析库,可以直接设置文本内容
// document.getElementById(targetElementId).innerText = markdown;
// })
// .catch(error => console.error(`Error loading ${markdownFile}:`, error));
// }
// updateSidebarContent('./assets/information.md', 'informationContent');
// updateSidebarContent('./assets/extended_outlook.md', 'extendedOutlookContent');通过本教程,我们学习了如何在JavaScript中利用 async/await 语法优雅地处理异步数据加载,并解决了因异步操作导致的变量作用域问题。关键在于将 DOMContentLoaded 回调函数声明为 async,并在需要异步数据的地方使用 await 关键字,确保数据在被使用前已经准备就绪。同时,我们也强调了在浏览器环境下使用 fetch API时关于文件路径的注意事项,以及错误处理的重要性,这些都是构建健壮Web应用的基础。
以上就是JavaScript中异步加载JSON数据并解决作用域问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号