HTML5 LocalStorage:检查密钥是否存在 [英] HTML5 LocalStorage: Checking if a key exists

查看:42
本文介绍了HTML5 LocalStorage:检查密钥是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};

目标是将用户从索引页面重定向到登录页面(如果尚未登录).这里 localStorage.getItem("username")) 变量暂时没有定义.

The goal is to redirect the user from the index page to the login page if not already logged. Here the localStorage.getItem("username")) variable is not defined for the moment.

适用于 ios phonegap 应用程序.

It's for an ios phonegap app.

推荐答案

引用自 规范:

getItem(key) 方法必须返回与给定键关联的当前值.如果给定的键不存在于与对象关联的列表中,则此方法必须返回 null.

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

您实际上应该检查 null.

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

这篇关于HTML5 LocalStorage:检查密钥是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆