只是一个简单的问题。当您有一个包含普通函数、变量和其他内容的 js 文件时,该页面将被加载,然后在需要代码时使用。但我的问题是,例如,当您导航到另一个页面(例如使用 window.location.href)时,您创建的任何/所有变量会发生什么?它们还存在于内存中吗?它们还能以某种方式访问吗?或者它们会永远消失,直到您重新加载原始文件为止?
干杯
最佳答案
简短回答:是。
存储在 JS 文件中的每个变量都会丢失,或者说,每次重新加载页面或更改 Window.location.href 时都会创建一个新副本。
要保留数据或在重新加载之间使用变量的值,您应该使用客户端数据存储,例如 sessionStorage
或 localStorage
或 cookies
.
例如,假设要使用持久变量的值,您可以使用
let persist = "My data";
// Store it in localstorage
localStorage.set('persist', persist);
// Get the value of your saved variable to use it elsewhere
let persist = locastorage.get("persist");
//To delete the variable from storage
localStorage.removeItem('persist')
// To clear the entire storage
localStorage.clear()
语法与 sessionStorage
相同,但使用 sessionStorage
存储的值仅在页面 session 期间可用。有关 DOM 存储的更多信息,您可以阅读 here .
关于javascript - 加载新的 html 页面时,JS 变量是否会被销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727555/