Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 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 Answer

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:(看到这个相关的问题:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...