[英]Push function is not working properly localStorage Javascript vanilla
我正在做一个点击时间游戏,你可以想象最快的时间将是第一位的。 我只想得到3分。 并将其保存在本地存储中,但每次我开始新游戏时,实际分数都会重置其值,并且不会产生其他分数。 3 个分数的值应为 0。我尝试将它们推为 arrays 但推 function 效果不佳。 在这一点上,我被困住了。 我不知道该怎么办。 如果你能帮助我,我将不胜感激,谢谢!
let times = Array.from({
length: 3
})
let interval2;
// Timer CountUp
const timerCountUp = () => {
let times = 0;
let current = times;
interval2 = setInterval(() => {
times = current++
saveTimes(times)
return times
}, 1000);
}
// Saves the times to localStorage
const saveTimes = (times) => {
localStorage.setItem('times', JSON.stringify(times))
}
// Read existing notes from localStorage
const getSavedNotes = () => {
const timesJSON = localStorage.getItem('times')
try {
return timesJSON ? JSON.parse(timesJSON) : []
} catch (e) {
return []
}
}
//Button which starts the countUp
start.addEventListener('click', () => {
timerCountUp();
})
// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {
console.log('click');
times.push(score = interval2)
getSavedTimes()
if (interval) {
clearInterval(interval);
clearInterval(interval2);
}
})
这个:
// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {
大概应该是这样的:
// Button which stops the countUp
document.querySelector('#stop_button').addEventListener('click', (e) => {
...考虑到您已经在前面的语句中附加了一个事件处理程序来start
'click'
事件,并且没有人会使用#start_button
作为停止按钮的id=""
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.