js 本地緩存localStorage


1.localStorage - 沒有時間限制的數據存儲 

   var arr=[1,2,3];
   localStorage.setItem("stor",arr); 
   console.log(localStorage.getItem("stor"));

 2.清空localStorage
  localStorage.clear(); //

 3.刪除鍵值對
  localStorage.removeItem("stor");  
  注意:存入的數據只能以字符串形式存入。


//JSON對象轉JSON字符串
  var obj = {"a": 1,"b": 2};
  obj = JSON.stringify(obj); //轉化為JSON字符串
  localStorage.setItem("stor1", obj);

  //JSON字符串轉JSON對象
  obj=JSON.parse(localStorage.getItem("stor1"));

 例如 6個元素 每次刷新頁面依次出現一個(不重復出現),最后一個元素出現后從新開始:

<script>
// JavaScript Document
tips = new Array(6);
tips[0] = 'K6661112228';
tips[1] = 'sy66688815';
tips[2] = 'y6668887788';
tips[3] = 'xzc17051001008';
tips[4] = 'Yn6661118882255';
tips[5] = '258258005858';

var i=localStorage.getItem("index");
if(i==null)
{
    index=0;
    localStorage.setItem("index", "0")
}else
{
    
    var i=localStorage.getItem("index");
        index=parseInt(i)+1;
        if(index>5)
        {
                index=0;
    localStorage.setItem("index", "0")
        }else{
            localStorage.setItem("index", index)
        }
}
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM