在 JavaScript 中重新分配全局变量 - 有人可以向我解释为什么 currentAcc 未定义

问题描述

所以基本上我在一个没有 .addEventlistener() 的简单测试场景中尝试了同样的事情并且它可以工作但我没有让它工作,currentAcc 在全局范围内保持未定义并且不接受函数的赋值。我非常感谢您的帮助。

data <- read.csv("DataSet.2.csv",header=TRUE,row.names = 1)
row_sum <- rowSums(data,na.rm = TRUE)
col_sum <- colSums(data,na.rm = TRUE)

解决方法

JavaScript 解释器在执行之前不会进入函数体。

这是解释器如何执行您的代码的简化示例:

let currentAcc; // empty variable declaration

function logIn() {} // function declaration,doesn't enter,only saves a pointer to it into the memory

console.log(currentAcc) // undefined,because `currentAcc` is still empty

function init() {} // function declaration

init() // function execution,now interpreter goes into the body of `init` func and so on

因此,根据您发布的代码,currentAcc 变量保持 undefined 直到用户点击。

如果您需要在页面之间传递数据,请考虑使用 window.localStoragewindow.sessionStorage

如果您需要更多帮助,请发布 Minimal,Reproducible Example,以便我可以帮助您处理一些实际代码。