Javascript数字存储

qij5mzcb  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(79)

我想做一个计算器并将数字保存在Javascript LocalStorage中,但下面的代码不起作用。

const x = [24];

function test() {
  for (let i = 4; i > 0; i--) {
    if (i == 1) {
      localStorage.setItem(0, x[0]);
    } else {
      localStorage.removeItem(i);
      localStorage.setItem(i, x[i - 1]);
      console.log(i);
      console.log(x[i - 1]);
    }
  }
}

我的目标是,数字是“移动”的数字,以便当我点击按钮“计算”的数字是,例如从数组[1, 35, 12, 35, 13]移动到数组[new Number, 1, 35, 12, 35]。我想为最后5个数字创造一个历史,第6个数字总是会被删除。但是我不知道怎么做我试了很多
我试着修改代码,我做了一个if语句,但总是不起作用

nqwrtyyt

nqwrtyyt1#

读一次,更新时写
Working example

window.addEventListener("DOMContentLoaded", () => { // when page loads
  const arr = JSON.parse(localStorage.getItem("arr") || '[]'); // load or create
  const saveNumber = num => {
    arr.unshift(num); // add to start
    if (arr.length === 6) arr.pop(); // remove from end
    localStorage.setItem("arr",JSON.stringify(arr));
  };
  // delegate from button container
  document.getElementById("calculator").addEventListener("click", (e) => {
    const tgt = e.target.closest("button.num"); // what was clicked?
    if (!tgt) return; // only handle number buttons
    saveNumber(+tgt.textContent);
  });
});

HTML:

<div id="calculator">
  <button class="num">1</button> 
  <button class="num">2</button> 
  <button class="num">3</button> 
  <button class="num">4</button> 
  <button class="num">5</button> 
  <button class="num">6</button> 
  <button class="num">7</button> 
  <button class="num">8</button> 
  <button class="num">9</button> 
  <button class="num">0</button> 
</div>

相关问题