【问题标题】:Increment localStorage value by one将 localStorage 值加一
【发布时间】:2021-04-30 17:58:45
【问题描述】:

我正在为我们的应用程序尝试登录功能。他们失败了三次,这完全把他们踢了出去。为了计算他们尝试了多少次,我想我会使用 localStorage,因为我可以轻松操作它。但是,当他们无法对自己进行身份验证时,我无法增加值。

在顶部,我正在设置 localStorage 变量

localStorage.setItem("attempts", "0")

然后如果服务器返回错误,我会尝试增加该值。

if(errorCode === 4936){
  var attempts = localStorage.getItem("attempts");
  localStorage.setItem(attempts++);
  console.log(attempts);
}

显然这不起作用,但是当我研究设置和获取 localStorage 时,我所能找到的只是更新或更改。任何帮助都会很棒!

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    而且在某些情况下,您必须在 尝试 之前添加 ++

    if (errorCode == 4936) {
      var attempts = parseInt(localStorage.getItem("attempts"));
      localStorage.setItem("attempts", ++attempts);
      console.log(attempts);
    }
    

    【讨论】:

    • 我收到错误 Uncaught ReferenceError: Invalid left-hand side expression in postfix operation when I put this in.
    • 已编辑。你不能++ 不是变量的东西。我忽略了它
    【解决方案2】:

    根据localstoragesetItem的文档只接受DomString(UTF-16 String)。所以答案应该是

    if (errorCode === 4936) {
     var attempts = (parseInt(localStorage.getItem('attempts'))+1);
     localStorage.setItem("attempts", attempts.toString());
     console.log(attempts);
    }
    

    【讨论】:

      【解决方案3】:

      这里有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);
      }
      

      【讨论】:

      • 是的,当我将引号从 0 中取出时,它会对我大喊大叫,因为 localStorage 只会接受字符串。这似乎工作一次,但是当它通过函数返回时,它只是停留在“1”
      • 你是绝对正确的。我刚试了一下,数字在存储时会自动转换为字符串。更新了我的答案以反映这一点
      • 哦,我真的有一个更大的标志在那里它一定是我复制粘贴的时候被删除了。似乎我仍然不能比第一次运行时增加更多的数字。一旦达到 1,它就会保持在 1。
      • 您确定localStorage.setItem("attempts", "0"); 部分不会多次运行吗?
      • 我也把attempts++改成了++attempts
      【解决方案4】:

      你应该这样使用。它对我有用。

      if(errorCode === 4936){
        var attempts = parseInt(localStorage.getItem("attempts"));
        localStorage.setItem("attempts",`${++attempts}`);
        console.log(attempts);
      }
         

      【讨论】:

        【解决方案5】:

        接受的答案并不真正正确,因为如果项目 attempts 在 localStorage 中不存在:

        localStorage.getItem('attempts') // null
        parseInt(null) // NaN
        

        打字稿中的正确方式是

         const currentAttempts = parseInt(localStorage.getItem('attempts') ?? '0')
         localStorage.setItem('attempts', (currentAttempts + 1).toString())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-08
          • 2020-12-08
          • 1970-01-01
          • 2015-10-24
          • 2020-03-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多