简体   繁体   English

如何将数组保存到会话存储?

[英]How do you save an array to session storage?

I've read a few similar threads, but the solutions are not working for me.我已经阅读了一些类似的主题,但这些解决方案对我不起作用。 The page I am working on has filters for a gallery of images.我正在处理的页面具有用于图像库的过滤器。 Each time I click on a filter the images with reload according to that filter via a JSON file.每次我点击过滤器时,都会根据该过滤器通过 JSON 文件重新加载图像。

If I want to apply multiple filters I would need the ones chosen prior to the reload to save in an array variable.如果我想应用多个过滤器,我需要在重新加载之前选择的过滤器以保存在数组变量中。

This is the code I have for this这是我的代码

let filterArray = []

sessionStorage.setItem('filterArray', JSON.stringify(filterArray))

let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))

Right now I don't have the page reload set up but after clicking on a filter and refreshing the page I would expect to be able to log the 'savedArr' variable but when I do I get this:现在我没有设置页面重新加载,但是在单击过滤器并刷新页面后,我希望能够记录“savedArr”变量,但是当我这样做时,我得到了这个:

Uncaught ReferenceError: savedArr is not defined at :1:13未捕获的 ReferenceError:savedArr 未在 :1:13 定义

You can't log savedArr after you refresh the page, you need to redefine it.刷新页面后无法记录savedArr ,需要重新定义。

The data in session storage will persist, but your variable declarations will not.会话存储中的数据将持续存在,但您的变量声明不会。

Call the declaration line again after you reload the page and you will have access to the data.重新加载页面后再次调用声明行,您将可以访问数据。

let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM