将本地存储值递增 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个问题

  1. 您需要在递增之前将尝试次数转换为数字

  2. 在第二个 set 语句中,您不会再次指定键

  3. 您正在分配错误代码,而不是检查它是否等于 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())