将数据对象整数添加到localstorage

时间:2018-04-18 16:55:01

标签: javascript local-storage

我想添加从服务器返回的数据对象并将它们存储在本地存储中。

data.Total是一组在成功请求时来自服务器的整数。 在将它们存储在本地存储

之前,我需要添加它们
let score = data.Total+localStorage.getItem("RelationScore");
let removeNull = score.replace('null', '');
localStorage.setItem("RelationScore", removeNull );

示例输出:1234

我想添加它们并将它们存储到单个变量中,因此基于该示例的结果应为10

3 个答案:

答案 0 :(得分:1)

根据您的评论,您可能正在寻找此代码:

let stored = (localStorage.getItem("RelationScore") === null ? 0 : parseInt(localStorage.getItem("RelationScore")));
let score = parseInt(data.Total) + stored;
localStorage.setItem("RelationScore", score);

答案 1 :(得分:1)

所有项目都以字符串形式保存到localStorage,因此您需要先解析它们:

let score = localStorage.getItem("RelationScore");
score = score === null ? 0 : parseInt(score);
localStorage.setItem("RelationScore", data.Total + score);

我假设data.Total是一个整数,就像你说的那样。如果不是,那么你也必须解析它。

如果您只想在项目不为零时更新总计:

let score = localStorage.getItem("RelationScore");
if(score !== null) {
    score = parseInt(score);
    if(score !==0)
        localStorage.setItem("RelationScore", data.Total + score);
}

答案 2 :(得分:0)

即使您将Integer放入localStorage,它也会被保存为String。

如果在JavaScript中向String添加数字,则只需将数字附加到字符串"10" + 1234 === "101234";即可。因此,您需要将String解析为数字:

let score = 0;

if (localStorage.getItem("RelationScore")) { // if the Item exists 
  score += parseInt(localStorage.getItem("RelationScore")); // make a number out of it and add it to the score
}

score += parseInt(data.Total); // add data.Total, even if the Item hasn't already been set

localStorage.setItem("RelationScore", score); // finally save the score to localStorage