我如何简化ParseInt从本地存储变量检索的代码块

我正在设计这个游戏,我在其中将1或0值作为正确或不正确的答案存储在变量q1-q6的本地存储中。

由于本地存储不会将数字存储为整数,因此在我的主页加载之前,我会parseInt所有变量获取整数。尽管其中一些还没有被声明为任何东西,所以它们似乎是NaN或null,因此,当我尝试计算所有变量的加法运算时,除非我使用此乱七八糟的代码,否则它会给我NaN。

    if (isNaN(totalpoints)) totalpoints = 0;
    if (localStorage.getItem("points") === null){
    localStorage.setItem("points", "0");
    }
    var q0 = parseInt(localStorage.q0);
    var q1 = parseInt(localStorage.q1);
    var q2 = parseInt(localStorage.q2);
    var q3 = parseInt(localStorage.q3);
    var q4 = parseInt(localStorage.q4);
    var q5 = parseInt(localStorage.q5);
    var q6 = parseInt(localStorage.q6);
    if (isNaN(q0))q0=0;
    if (isNaN(q1))q1=0;
    if (isNaN(q2))q2=0;
    if (isNaN(q3))q3=0;
    if (isNaN(q4))q4=0;
    if (isNaN(q5))q5=0;
    if (isNaN(q6))q6=0;
    var totalpoints = totalpoints + q0 + q1 + q2 + q3 + q4 + q5 + q6;
    localStorage.setItem("points", totalpoints);

我正在尝试一种方法,可以使用循环将变量简化为几行,从而将代码简化为几行? 谁能给我关于如何解决或帮助我的任何方向感? 我只是不确定,因为好像我必须单独解析所有localstorage变量? 谢谢

评论
Ruth
Ruth

我建议用一个数组替换多个值。 因此,您的保存功能可能如下所示:

function savePoint(point) {
  var points = JSON.parse(localStorage.points || "[]");
  points.push(point);
  localStorage.points = JSON.stringify(points);
}

您将像这样计算总数:

function calculateTotal() {
  var points = JSON.parse(localStorage.points || "[]");
  return points.reduce(function(total, point) {
    return total + point;
  }, 0);
}
点赞
评论
最后的最后
最后的最后

与其使用多个单独的数字索引属性,不如考虑使用单个数组:

const qArr = localStorage.qArr
  ? JSON.parse(localStorage.qArr)
  : new Array(7).fill(0);

Then, instead of assigning to the q variables, assign to an index of the qArr, and to save it, use JSON.stringify:

qArr[3] = 555;
localStorage.qArr = JSON.stringify(qArr);

To add up all the items in the array, you can use reduce:

totalPoints = qArr.reduce((a, b) => a + b, totalPoints);

Since it sounds like this is all in one self-contained script, I'd highly recommend consolidating all the relevant items that need to be stored into a single object too, if at all possible, so as not to pollute localStorage with lots of separate properties that really deserve to be in a single place, rather than spread out, eg:

const dataObj = localStorage.pointsData
  ? JSON.parse(pointsData)
  : {
      totalPoints: 0,
      qArr: new Array(7).fill(0)
    };

Then, do stuff with dataObj.totalPoints and dataObj.qArr, and when you need to save it, do something like:

localStorage.pointsData = JSON.stringify(dataObj);
点赞
评论
烦恼%
烦恼%

我建议一个对象。

You can store object as answers in localStorage and update the values.

So suppose answers object is something like this

answers = {
   q0: 10,
   q2: 20
}

然后,是否存在密钥都没有关系,因为您可以遍历对象以获得总和

let total = 0;

for (const key in answers) {
    total += answers[key];
}
点赞
评论