将本地存储值递增 1
Increment localStorage value by one
本文关键字:存储 更新时间:2023-09-26
我正在尝试为我们的应用程序提供登录功能。他们失败了三次,完全把他们踢出去了。为了记录他们尝试的次数,我想我会使用 localStorage,因为我可以轻松操作它。但是,当他们无法进行身份验证时,我无法增加值。
在顶部,我正在设置本地存储变量
localStorage.setItem("attempts", "0")
然后,如果服务器返回错误,我正在尝试增加该值。
if(errorCode === 4936){
var attempts = localStorage.getItem("attempts");
localStorage.setItem(attempts++);
console.log(attempts);
}
显然这是行不通的,但是当我研究时,我所能找到的就是设置和获取本地存储,没有任何关于更新或更改的内容。任何帮助都会很棒!
在某些情况下,您必须在尝试之前添加++:
if (errorCode == 4936) {
var attempts = parseInt(localStorage.getItem("attempts"));
localStorage.setItem("attempts", ++attempts);
console.log(attempts);
}
根据 localstorage 的文档setItem
只接受 DomString(UTF-16 String)。所以答案应该是
if (errorCode === 4936) {
var attempts = (parseInt(localStorage.getItem('attempts'))+1);
localStorage.setItem("attempts", attempts.toString());
console.log(attempts);
}
这里有3个问题
-
您需要在递增之前将尝试次数转换为数字
-
在第二个 set 语句中,您不会再次指定键
-
您正在分配错误代码,而不是检查它是否等于 4936
localStorage.setItem("attempts", "0");
if(errorCode == 4936){ // double equal is need to compare. Single equals is an assignment operator
var attempts = Number(localStorage.getItem("attempts"));
localStorage.setItem("attempts", ++attempts);
console.log(attempts);
}
你应该这样使用。它对我有用。
if(errorCode === 4936){
var attempts = parseInt(localStorage.getItem("attempts"));
localStorage.setItem("attempts",`${++attempts}`);
console.log(attempts);
}
接受的答案并不真正正确,因为如果 localStorage 中不存在该项attempts
:
localStorage.getItem('attempts') // null
parseInt(null) // NaN
打字稿的正确方式将是
const currentAttempts = parseInt(localStorage.getItem('attempts') ?? '0')
localStorage.setItem('attempts', (currentAttempts + 1).toString())
相关文章:
- 将作用域存储在JSON中
- 使用javascript存储变量的最安全方式
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- 如何有效地将游戏数据存储在URL查询字符串中
- Ember.js-接口状态应该存储在哪里
- 如何解雇“;铁局部存储负载”;事件
- 本地存储中的字符串到字节数组转换
- 从jQuery调用存储在Variable中的函数
- 推荐在JavaScript中执行存储为字符串的函数,而不是使用eval
- 通过另一个php应用程序将我的项目推送到Github存储库中
- 将数据存储在javascript数组中以供进一步使用
- 在页面卸载时写入HTML5 FileSystem API存储
- 加载存储在IndexedDB中的HTML页面
- 在字符串中查找所有图像 src URL 并存储在数组中
- 如何从C#代码背后调用本地存储的javascript函数
- 在ListView中添加JSON数组中存储的图像-ReactNative
- 将数据存储到元素中
- 使用ajax下载与存储名称不同名称的文件
- 将脚本缓存到本地存储的basket.js概念仍然是一个好主意吗