[英]Adding data objects integers to localstorage
我想添加從服務器返回的數據對象,並將它們存儲在本地存儲中。
data.Total
是一組在成功請求時來自服務器的整數。 我以某種方式需要將它們添加到本地存儲之前
let score = data.Total+localStorage.getItem("RelationScore");
let removeNull = score.replace('null', '');
localStorage.setItem("RelationScore", removeNull );
示例輸出: 1234
我想將它們添加並存儲到單個變量中,因此基於示例的結果應為10
根據您的評論,您可能正在尋找以下代碼:
let stored = (localStorage.getItem("RelationScore") === null ? 0 : parseInt(localStorage.getItem("RelationScore")));
let score = parseInt(data.Total) + stored;
localStorage.setItem("RelationScore", score);
所有項目都以字符串形式保存到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);
}
即使將Integer放入localStorage,它也將另存為String。
如果在JavaScript中將數字添加到字符串中,則只是將數字附加到字符串中, "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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.