【问题标题】:How do I handle the null string from received from local storage如何处理从本地存储接收的空字符串
【发布时间】:2020-05-02 18:59:21
【问题描述】:
<script type="text/javascript">

       function addfav(favor){
         // let a=String(favor.value)
         // console.log(a)
         // console.log(favor)

         let b=document.getElementById(favor).parentElement.parentElement.id
         console.log(b)
         let str=JSON.parse(localStorage.getItem("Favorites"))
         //What to do if str is null?
         str.push(b);
         localStorage.setItem("Favorites", JSON.stringify(str))
         document.getElementById(b).style="background-image: linear-gradient(to right,#5F0A87,#A4508B);";
       }
     </script>
     <script type="text/javascript">
       function getfav(){
         let i=0;
         var str=JSON.parse(localStorage.getItem("Favorites"))
         console.log(str)

         for(i=0;i<str.length;i++){
           document.getElementById(str[i]).style="background-image: linear-gradient(to right,#5F0A87,#A4508B);";
           console.log(document.getElementById(str[i]))
         }

       }


     </script>

最初,当我最喜欢的列表为空时,它显示为 null,我无法附加任何内容/推送任何内容

上面给出的是addfav和getfav函数,其中addfav由点击触发,getfav在页面加载时触发

有什么方法可以防止 null 发生/处理 null str?

【问题讨论】:

  • 问题是什么?在页面加载时执行一个函数,读取 localStorage (.getItem()) 并更改元素。
  • 你能分享一个sn-p吗?
  • Google(或您的首选搜索提供商)可以帮助您。

标签: javascript html css local-storage


【解决方案1】:

使用前检查str的值...

例子:

let str = JSON.parse(localStorage.getItem("Favorites"));
if (!Array.isArray(str)) {
  str = [];
}
// Use str as an array...

【讨论】:

  • 非常感谢!我是初学者,所以我不知道这样的操作!
  • 当我在本地运行页面时它可以工作,但是,当我将它上传到 github 页面时,它不起作用,它会生成此错误 VM103:1 Uncaught SyntaxError: Unexpected token c in JSON at position 0
  • 听起来你存储在 localStorage 中的 JSON 无效。你检查过你得到的价值吗?
  • 所以我只需要在 getfav() 函数中使用你给定的 sn-p !干杯!
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2012-12-10
  • 2020-11-28
  • 2013-12-13
相关资源
最近更新 更多