为本地存储添加高分
Adding a high score to local storage
我想为我的游戏增加一个高分。现在我有这个:
var score = 0;
var highscore = 0;
分数变量是有效的,但每当我得到类似的分数,总共60分时,它就会说,当使用console.log(highscore)
检查时,高分仍然为零。
我有这个存储高分:
if (score > localStorage.getItem("highscore")) {
localStorage.setItem("highscore", score);
}
这不能正常工作,但也不会产生任何错误。
试试这个:
var score = 0;
var highscore = localStorage.getItem("highscore");
if(highscore !== null){
if (score > highscore) {
localStorage.setItem("highscore", score);
}
}
else{
localStorage.setItem("highscore", score);
}
除了parseInt
,您还需要首先在localStorage
上设置init值,因为如果未设置,localStorage.getItem("highscore",10)
不会返回10作为默认值
var score = 0;
var highscore = 0;
localStorage.setItem("highscore",0);
因为当你检查时
if (score > parseInt(localStorage.getItem("highscore"))) {
localStorage.setItem("highscore", score);
}
如果项目尚未设置,则localStorage.getItem("highscore")
将返回null。或者你也可以做:
var storagedHighScore = localStorage.getItem("highscore");
if (storagedHighScore || score > parseInt(storagedHighScore)) {
localStorage.setItem("highscore", score);
}
您需要使用从localStorage检索值
highscore = +localStorage.getItem("highscore")
或一些等效代码。localStorage
中的项不跟踪具有相同名称的全局变量。
if (score > parseInt(localStorage.getItem('highscore'), 10)) {
localStorage.setItem('highscore', score);
}
在比较之前转换为int。其字符串
我刚刚在中查看了您的代码http://jsfiddle.net/unb8yLj3/我找不到你在哪一部分增加了分数,所以当这部分代码运行分数为0时localStorage.getItem("highscore")为10,因此它不设置highscore。
if (score > localStorage.getItem("highscore")) {
localStorage.setItem("highscore", score);
}
}
有没有另一个js文件可以提高分数?
相关文章:
- 在ListView中添加JSON数组中存储的图像-ReactNative
- 为本地存储添加高分
- 选择文本并添加到本地存储
- 将新对象添加到本地存储
- 如何将类似类型的多个对象添加到本地存储中
- 尝试将对象添加到存储阵列中,然后通过循环将它们写出
- 存储对追加动态添加的元素的引用
- 添加隐藏属性以存储其他属性值
- 如何在Javascript中向存储类添加自定义方法
- 如何将添加到列表框客户端的值存储到sessionScope
- 将本地存储密钥添加到下拉列表中
- 使用 jQuery 在本地存储上添加产品
- 检查本地存储中的记录是否在 1 分钟前添加
- 如何将动态添加的内容存储到数据库
- 如何在存储加载之前向面板添加遮罩,并在存储加载后删除
- 动态添加文本框并将其值存储在 mysql 中
- 将值添加到本地存储,而不是替换它
- 将对象添加到本地存储中的数组
- 将新对象添加到 chrome 本地存储
- 在 Extjs 网格(3)上添加存储数据