首页 > 解决方案 > JavaScript在localStorage中存储整数,增加值并渲染数据

问题描述

对于我的程序,用户输入一个数字以查看这是否与计算机猜测相符。为了简单起见,我可以更好地看到代码的流程,猜测的数字在 0-1 之间。我遇到的问题是我没有正确地将数据保存到 localStorage 并增加键值,如果我手动将值添加到我的键 localStorage 仅在我刷新页面时正确更新,每次我猜测程序似乎响应正确,但猜测后必须刷新。对于任何反馈,我们都表示感谢。

索引.html

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guess # | Main</title>
</head>
<body>
    <h1>Guess Number Between 0-1</h1>
    <form>
        <input id="enter-value" placeholder="Enter a number"></input>
        <button id="submit-number">Submit</button>
        <button id="reset-button">Reset</button>
    </form>
    <div id="result-section"></div>
    <div id="count-section"></div>
    <script src="functions.js"></script>
    <script src="dom.js"></script>
</body>
</html>

dom.js

    const submitNumber= document.getElementById('submit-number')
    const enterValue= document.getElementById('enter-value')
    const resultSection= document.getElementById('result-section')
    const countSection= document.getElementById('count-section')
    const resetButton= document.getElementById('reset-button')

    submitNumber.addEventListener('click', function(e){
        e.preventDefault()
        resultSection.textContent=''
        countSection.textContent=''
        const userNumInput= enterValue.value.trim()
        userGuess(userNumInput)
    })

    resetButton.addEventListener('click', function(e){
        e.preventDefault()
        localStorage.clear()
        countSection.textContent=''
        resetField()
        resultSection.textContent=''
    })

functions.js

let userTallyTotal
let computerTallyTotal 

const userGuess= (userNumber)=>{
    let message=''
    localStorage.getItem('userWinsTotal')!= null ? userTallyTotal : userTallyTotal= 0
    localStorage.getItem('computerWinsTotal')!= null ? computerTallyTotal : computerTallyTotal= 0
    //Current problem I'm facing now is that refreshing the page and submitting a value changes localStorage value to NaN

    let numberChoice= userNumber
    const randomNum= Math.floor(Math.random()*1)
    numberChoice= parseInt(numberChoice, 10)

    if (isNaN(numberChoice)){
        message+= 'This is not a number, try again.'
        displayResult(message)
        resetField()
        return
    }

    if (numberChoice===randomNum) {
        parseInt(userTallyTotal, 10)
        userTallyTotal++
        localStorage.setItem('userWinsTotal', userTallyTotal)
        message+= `You won! You guessed: ${numberChoice} and the computer guessed: ${randomNum}`
    } else {    
        parseInt(computerTallyTotal, 10)
        computerTallyTotal++
        localStorage.setItem('computerWinsTotal', computerTallyTotal)
        message+= `Sorry Try Again! You guessed: ${numberChoice} and the computer guessed: ${randomNum}`
    }
        resetField()
        displayResult(message)
        countWins(userTallyTotal,computerTallyTotal)
}

const displayResult= (message)=>{    
    const displayResultEl= document.createElement('h2')
    displayResultEl.textContent= message
    document.getElementById('result-section').appendChild(displayResultEl)
}

const countWins= (userTallyTotal, computerTallyTotal)=>{   
    const countWinsEl= document.createElement('h2')
    countWinsEl.textContent= `User Total Win: ${userTallyTotal} Computer Total Win: ${computerTallyTotal}`
    document.getElementById('count-section').appendChild(countWinsEl)
}

const resetField= ()=>{
    enterValue.value=''
    enterValue.focus()
}

标签: javascriptlocal-storage

解决方案


我发现了所有问题:

1.localStorage正如@Yesset Zhussupov 所提到的,只能存储字符串,因此重新加载时您需要解析您的常量:

const userTallyTotal= parseInt(localStorage.getItem('userWinsTotal'))
const computerTallyTotal= parseInt(localStorage.getItem('computerWinsTotal'))
  1. userGuess您每次都打电话并重置您的计数器:
userWinsTotal= userTallyTotal
computerWinsTotal= computerTallyTotal

whereuserTallyTotalcomputerTallyTotalare const-type。
解决这个问题很简单:

userWinsTotal= userWinsTotal||userTallyTotal
computerWinsTotal= computerWinsTotal||computerTallyTotal

它将检查该变量是否已初始化


推荐阅读