如何查看Storage项是否设置?

发布于 2024-09-10 11:06:38 字数 314 浏览 10 评论 0原文

如何检查 localStorage 中是否设置了某个项目?目前我正在使用

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

How can I check if an item is set in localStorage? Currently I am using

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

剩余の解释 2024-09-17 11:06:38

WebStorage 规范中的 getItem 方法,显式返回 null 如果该项不存在:

...如果给定的键不存在于与该对象关联的列表中,则此方法必须返回 null。 ...

因此,您可以:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

查看此相关问题:

The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:

... If the given key does not exist in the list associated with the object then this method must return null. ...

So, you can:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

See this related question:

○闲身 2024-09-17 11:06:38

您可以使用 hasOwnProperty 方法来检查此

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

功能在当前版本的 Chrome(Mac)、Firefox(Mac) 和 Safari 中是否有效。

You can use hasOwnProperty method to check this

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.

寂寞花火° 2024-09-17 11:06:38

如果密钥不在存储中,最短的方法是使用默认值:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */

The shortest way is to use default value, if key is not in storage:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */
笨笨の傻瓜 2024-09-17 11:06:38

有几种方法可以检查,我在这里添加它们

方法 1

if("infiniteScrollEnabled" in localStorage){
     console.log("Item exists in localstorage");
}else{
    console.log("Item does not exist in localstoarge";
}

方法 2

if(localStorage.getItem("infiniteScrollEnabled") === null){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

方法 3

if(typeof localStorage["cart"] === "undefined"){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

方法 4

if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
     console.log("Item exists in localstorage");
 }else{
    console.log("Item does not exist in localstoarge";
 }

there are couple of methods to check i am adding them here

Method 1

if("infiniteScrollEnabled" in localStorage){
     console.log("Item exists in localstorage");
}else{
    console.log("Item does not exist in localstoarge";
}

Method 2

if(localStorage.getItem("infiniteScrollEnabled") === null){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

Method 3

if(typeof localStorage["cart"] === "undefined"){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

Method 4

if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
     console.log("Item exists in localstorage");
 }else{
    console.log("Item does not exist in localstoarge";
 }
风轻花落早 2024-09-17 11:06:38
if(!localStorage.hash) localStorage.hash = "thinkdj";

var secret =  localStorage.hash || 42;

更新:

let scrollEnabled = localStorage?.scrollEnabled??true;
if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

Updated:

let scrollEnabled = localStorage?.scrollEnabled??true;
酒绊 2024-09-17 11:06:38

可以尝试这样的事情:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')

Can try something like this:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')
宁愿没拥抱 2024-09-17 11:06:38

如果您想检查是否未定义,也可以尝试此操作:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem 是一种如果未找到值则返回 null 的方法。

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.

这个俗人 2024-09-17 11:06:38

对于True

localStorage.infiniteScrollEnabled = 1;

或 False

localStorage.removeItem("infiniteScrollEnabled")

检查是否存在

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}
弥枳 2024-09-17 11:06:38

如何测试 localStorage 中是否存在一项?
此方法适用于 Internet Explorer。

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>

How can one test existence of an item in localStorage?
this method works in internet explorer.

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>
梦里人 2024-09-17 11:06:38

我建议的最好、最安全的方法是这样,

if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

它通过 ESLint 的 no-prototype -builtins 规则。

Best and Safest way i can suggest is this,

if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

This passes through ESLint's no-prototype-builtins rule.

对岸观火 2024-09-17 11:06:38

您应该检查 localStorage 中项目的类型

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}

You should check for the type of the item in the localStorage

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}
淡紫姑娘! 2024-09-17 11:06:38

我已经在我的项目中使用过并且非常适合我

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}

I've used in my project and works perfectly for me

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}
很酷不放纵 2024-09-17 11:06:38

我参加这个聚会迟到了,但是使用 localDataStorage,我创建的一个方便的实用程序包装器。

使用类似的方法实例化包装器后,

myLDS = localDataStorage( 'segmentedStorageHere' );

设置键

myLDS.set( 'infiniteScrollEnabled', true );

您可以以简单的方式 。请注意,此示例实际上将一个布尔值传递给存储,可以在存储中检索该值

let scrollingState = myLDS.get( 'infiniteScrollEnabled' );

,并且滚动状态将包含返回的布尔值。包装器无缝地为您跟踪本机 JavaScript 数据类型(数组、布尔值、日期、数字、对象等),代码中不再需要进行 JSON 字符串化/解析。

现在,当我们需要知道密钥是否在存储中时,我们可以像这样检查它。

if( myLDS.haskey( 'infiniteScrollEnabled' ) ) {
    console.log( "It's been set!" ); 
} else {
    console.log( "The key is not set." ); 
}

您还可以检查特定值是否存在。例如

myLDS.set( 'myNumber', 1234.5678 );
console.log( myLDS.hasval( 1234.5678 ) );    --> true

I'm late to this party, but checking localStorage for the existence of keys (or the existence of key values) is easily done with localDataStorage, a handy utility wrapper I created.

After instantiating the wrapper with something like

myLDS = localDataStorage( 'segmentedStorageHere' );

you can set keys

myLDS.set( 'infiniteScrollEnabled', true );

in a straightforward manner. Note that this example is actually passing a boolean value to the store, where it can be retrieved with

let scrollingState = myLDS.get( 'infiniteScrollEnabled' );

and scrollingState will contain the boolean value returned. The wrapper keeps track of the native JavaScript data type for you, seamlessly (Array, Boolean, Date, Number, Object, etc.) No more JSON stringifying/parsing in your code.

Now when we need to know if a key is in the store, we can check it like this

if( myLDS.haskey( 'infiniteScrollEnabled' ) ) {
    console.log( "It's been set!" ); 
} else {
    console.log( "The key is not set." ); 
}

You can also check whether a particular value is present. For example

myLDS.set( 'myNumber', 1234.5678 );
console.log( myLDS.hasval( 1234.5678 ) );    --> true
空袭的梦i 2024-09-17 11:06:38

正如 @Christian C. Salvadó 上面提到的,你可以这样做
if (xxx === null){}

但 null 也是一个假值,如下所示:

if (null){
console.log ("hello");
}

它不会打印“hello”。

As @Christian C. Salvadó has mentioned above you can do
if (xxx === null){}

but null is also a falsy value, like so:

if (null){
console.log ("hello");
}

which does not print "hello".

迷你仙 2024-09-17 11:06:38
localStorage['root2']=null;

localStorage.getItem("root2") === null //false

也许最好扫描一下计划?

localStorage['root1']=187;
187
'root1' in localStorage
true
localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Maybe better to do a scan of the plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true
风尘浪孓 2024-09-17 11:06:38

我总是通过检查 localStoragesessionStorage 的长度来检查它们是否已设置

if (sessionStorage.length > 0) {
  console.log("exists")
} else {
  console.log("not exists")
}


I always check if localStorage or sessionStorage is set by checking the length of them

if (sessionStorage.length > 0) {
  console.log("exists")
} else {
  console.log("not exists")
}


任性一次 2024-09-17 11:06:38

该代码

if (localStorage.getItem("infiniteScrollEnabled") === null) {

对我不起作用。也许是因为自从提供这个答案以来事情已经发生了变化。今天,2023 年,以下命令对我有用:

if (!localStorage.getItem("infiniteScrollEnabled")) {

请注意,这实际上是 MDN Web 文档中推荐的方法,网址为 https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_whether_your_storage_has_been_populated.

The code

if (localStorage.getItem("infiniteScrollEnabled") === null) {

is not working for me. Perhaps it's because things have changed since this answer was provided. Today, in 2023, the following command works for me:

if (!localStorage.getItem("infiniteScrollEnabled")) {

Note that this is actually the method recommended in the MDN web docs at https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_whether_your_storage_has_been_populated.

不知在何时 2024-09-17 11:06:38

试试这个代码

if (localStorage.getItem("infiniteScrollEnabled") === null) {

} else {

}

Try this code

if (localStorage.getItem("infiniteScrollEnabled") === null) {

} else {

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文