【问题标题】:Is there any way to avoid the undefined value of key of localStorage.getItem()?有什么办法可以避免 localStorage.getItem() 的 key 的未定义值?
【发布时间】:2023-03-18 10:10:01
【问题描述】:

我的本​​地存储中有以下密钥对值 - 仪器,BTX(键,值)。我从本地存储中手动删除了该值。现在这个键的值是未定义的。 我写了这个条件来避免未定义的值,但它不起作用。 这里的问题是,虽然值是未定义的,所以应该执行 else 块,但在所有可能的情况下,if 块都会被执行。

第一种方式:

if(localStorage.getItem("instrument")){}
else {}

第二种方式:

if(!!localStorage.getItem("instrument")){}
else {}

第三种方式:

if(localStorage.getItem("instrument")!==undefined){}
else {}

【问题讨论】:

  • 您指定了两种不同的方法来确定一个值是否 falsy,以及一种方法来检查它是否不是未定义的。那么你的问题是什么?
  • 嗨@RobbyCornelissen,在所有这些情况下,如果块正在运行,那么块应该运行。
  • localStorage 中有空对象吗?你可能认为空对象是虚假的,但事实并非如此。 Object.keys(obj).length > 0 可以是支票。
  • 您的任何if 块都不会检查该值是否未定义。他们都检查该值是否NOT undefined/falsy。
  • @RobbyCornelissen 你能帮忙解决这个问题吗?

标签: javascript reactjs frontend


【解决方案1】:

试试这个

if(localStorage.getItem("instrument")!=null){
// Do Something here
}else{
// Do Something Here
}

希望它有效:)

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2022-07-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多