Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

javascript - 如何检查存储项是否已设置?(How to check whether a Storage item is set?)

How can I check if an item is set in localStorage ?(如何检查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);
}
  ask by Jiew Meng translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:(WebStorage规范中的getItem方法,如果该项不存在,则显式返回null :)

... If the given key does not exist in the list associated with the object then this method must return null.(...如果给定键与对象关联的列表中不存在,则此方法必须返回null。)

...(...)

So, you can:(所以你可以:)

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

See this related question:(看到这个相关的问题:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...