我是一名 javascript 学习者,正在努力为我的 child (5 到 10 岁)设计一个小型 javascript 游戏,其中的分数是基于耗时。但是,我想不出总分的方法。我管理了下面的代码,但结果不准确。程序可能会在每次单击时对数组中的所有项目进行总计。有人可以帮忙吗?我是新手,这里会有很多错误或荒谬的地方,请您在指正我的同时礼貌地提供帮助。任何帮助表示赞赏..
document.getElementById("box1").onclick = function() {
clickT = Date.now();
reactT = (clickT - createdT) / 1000; //gets the time difference for reaction.
points = reactT * 1000;
points = 2000 - points;
pRecord.push(points); //add points to array.
for (i = 0; i < pRecord.length; i++) {
totalpoints += pRecord[i];
}
document.getElementById("time").innerHTML = reactT;
this.style.display = "none";
document.getElementById("score").innerHTML = totalpoints;
}
最佳答案
在对点求和之前,只需将 totalpoints
设置为零:
document.getElementById("box1").onclick = function() {
var clickT = Date.now();
var reactT = (clickT - createdT) / 1000; //gets the time difference for reaction.
var points = reactT * 1000;
points = 2000 - points;
pRecord.push(points); //add points to array.
var totalpoints = 0;
for (var i = 0; i < pRecord.length; i++){
totalpoints += pRecord[i];
}
document.getElementById("time").innerHTML = reactT;
this.style.display = "none";
document.getElementById("score").innerHTML = totalpoints;
}
而且我不知道你是否在外部范围内定义了你的变量,但我猜你没有,所以我在每个变量创建之前添加了 var
。
关于javascript - 我怎样才能正确地总分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971318/