Jie*_*eng 261 javascript html5 local-storage
如何检查项目是否已设置localStorage?目前我正在使用
if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
// init variable/set default variable for item
localStorage.setItem("infiniteScrollEnabled", true);
}
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 461
getItemWebStorage规范中的方法,null如果该项不存在,则显式返回:
...如果给定键与对象关联的列表中不存在,则此方法必须返回null....
所以你可以:
if (localStorage.getItem("infiniteScrollEnabled") === null) {
//...
}
Run Code Online (Sandbox Code Playgroud)
看到这个相关的问题:
Ste*_*yer 28
您可以使用hasOwnProperty方法来检查这一点
> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false
Run Code Online (Sandbox Code Playgroud)
适用于当前版本的Chrome(Mac),Firefox(Mac)和Safari.
Vla*_*lav 18
最短的方法是使用默认值,如果密钥不在存储中:
var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */
Run Code Online (Sandbox Code Playgroud)
有几种方法可以检查我在这里添加它们
方法一
if("infiniteScrollEnabled" in localStorage){
console.log("Item exists in localstorage");
}else{
console.log("Item does not exist in localstoarge";
}
Run Code Online (Sandbox Code Playgroud)
方法二
if(localStorage.getItem("infiniteScrollEnabled") === null){
console.log("Item does not exist in localstoarge";
}else{
console.log("Item exists in localstorage");
}
Run Code Online (Sandbox Code Playgroud)
方法三
if(typeof localStorage["cart"] === "undefined"){
console.log("Item does not exist in localstoarge";
}else{
console.log("Item exists in localstorage");
}
Run Code Online (Sandbox Code Playgroud)
方法4
if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
console.log("Item exists in localstorage");
}else{
console.log("Item does not exist in localstoarge";
}
Run Code Online (Sandbox Code Playgroud)
if(!localStorage.hash) localStorage.hash = "thinkdj";
Run Code Online (Sandbox Code Playgroud)
或者
var secret = localStorage.hash || 42;
Run Code Online (Sandbox Code Playgroud)
可以尝试这样的事情:
let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
292083 次 |
| 最近记录: |