gpt4 book ai didi

javascript - NOT 与 NULL 与本地存储

转载 作者:行者123 更新时间:2023-12-03 00:21:00 30 4
gpt4 key购买 nike

所以我想从本地存储中获取一个变量。如果本地存储中不存在它,那么我想创建该变量。我使用 if (x==null) 来查看它是否存在,然后我注意到 if(!x) 具有相同的结果。在这种情况下使用 ! 可以吗?我不知道 !null 在这里是相同的。另外,在检查 null 时,我应该使用 === 还是 == 可以吗?

这里有两个例子给了我相同的结果。

<script>
localStorage.clear();

a=localStorage.getItem('a');if (!a) a='hello';
alert(a);

x=localStorage.getItem('x');if (!x) x=0.7;
alert(x);

</script>
<小时/>
<script>
localStorage.clear();

a=localStorage.getItem('a');if (a==null) a='hello';
alert(a);

x=localStorage.getItem('x');if (x==null) x=0.7;
alert(x);

</script>

最佳答案

https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem

如果键不存在,

localStorage.getItem 将返回 null。因此,a === null 将是最具体的检查 key 是否不存在的方法。然而,null 在 javascript 中是 false。因此您可以将检查减少为:

a = localStorage.getItem('a') || '你好';

其功能与带有 not 运算符的 if 相同

关于javascript - NOT 与 NULL 与本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54313836/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com