如何用新的替换localstorage项

时间:2018-02-09 17:32:43

标签: angular typescript ionic-framework local-storage

我们尝试在localstorage中设置一个新项目。但只有它高于最后一项。我们的问题是if比较不起作用。有什么想法吗?

很抱歉,如果我们问一个愚蠢的问题,但我们只是初学者寻求帮助。非常感谢。

 saveList(){

 let newScore:any; //this is a numeric value pushed from another page
 newScore=this.newlist;


 localStorage.setItem("scores", (newScore));

 parseInt(localStorage.getItem( "score")) ;


 let highscore= parseInt( localStorage.getItem("scores"));



 if(newScore>highscore){ 

  localStorage.setItem("scores", (newScore));


}

  //let storedScores = JSON.parse(localStorage.getItem("scores"));   
}

3 个答案:

答案 0 :(得分:0)

因为如果本地存储中没有对象,localStorage.getItem()将返回null,你可以使用这个

saveList(){

 let newScore:any;  
 newScore=this.newlist;

 let highscore= parseInt( localStorage.getItem("scores")); 

 if(  highscore > newScore ){
  // do nothing 
 } else  { 
    localStorage.setItem("scores", (newScore));
  }
}

答案 1 :(得分:0)

您可以使用三元操作

saveList(){
    let newScore=this.newlist;
    let highscore= parseInt( localStorage.getItem("scores")); 
    localStorage.setItem("scores", ((newScore>highscore) ? newScore : highscore));
}   

答案 2 :(得分:0)

您可以考虑使用相同的键来替换本地项,就像这样...

var boo = "my boo"
var newBoo = "my new boo"

localStorage.setItem("foo", boo);        // foo: "my boo"

// replacing...
localStorage.setItem("foo", newBoo);     // foo: "my new boo"