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個元素 每次刷新頁面依次出現一個(不重複出現),最後一個元素出現後重新開始:spa

<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>
相關文章
相關標籤/搜索