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

查看:1002
本文介绍了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.

推荐答案

引用规范


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

你应该检查 null

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

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

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