localStorage用法總結

先看一下localStorage自帶的方法以下表:數組

名稱 做用
clear 清空localStorage上存儲的數據
getItem 讀取數據
hasOwnProperty 檢查localStorage上是否保存了變量x,須要傳入x
key 讀取第i個數據的名字或稱爲鍵值(從0開始計數)
length localStorage存儲變量的個數
propertyIsEnumerable 用來檢測屬性是否屬於某個對象的
removeItem 刪除某個具體變量
setItem 存儲數據
toLocaleString 將(數組)轉爲本地字符串
valueOf 獲取全部存儲的數據

 

 

 

 

 

 

 

 

 

 

 


 

 

清空localStorage

localStorage.clear()    // undefined    
localStorage            // Storage {length: 0}

存儲數據

 

localStorage.setItem("name","caibin") //存儲名字爲name值爲caibin的變量
 
localStorage.name = "caibin"; // 等價於上面的命令
 
localStorage // Storage {name: "caibin", length: 1}

 

讀取數據

 

localStorage.getItem("name") //caibin,讀取保存在localStorage對象里名爲name的變量的值
 
localStorage.name // "caibin"
 
localStorage.valueOf() //讀取存儲在localStorage上的全部數據
 
localStorage.key(0) // 讀取第一條數據的變量名(鍵值)
 
//遍歷並輸出localStorage裏存儲的名字和值
 
for(var i=0; i<localStorage.length;i++){
 
console.log('localStorage裏存儲的第'+i+'條數據的名字爲:'+localStorage.key(i)+',值爲:'+localStorage.getItem(localStorage.key(i)));
 
}

刪除某個變量

localStorage.removeItem("name"); //undefined
 
localStorage // Storage {length: 0} 能夠看到以前保存的name變量已經從localStorage裏刪除了

檢查localStorage裏是否保存某個變量

// 這些數據都是測試的,是在我當下環境裏的,只是demo哦~
 
localStorage.hasOwnProperty('name') // true
 
localStorage.hasOwnProperty('sex') // false

 

將數組轉爲本地字符串

var arr = ['aa','bb','cc']; // ["aa","bb","cc"]
localStorage.arr = arr //["aa","bb","cc"]
localStorage.arr.toLocaleString(); // "aa,bb,cc"

 

將JSON存儲到localStorage裏

var students = {
 
xiaomin: {
 
name: "xiaoming",
 
grade: 1
 
},
 
teemo: {
 
name: "teemo",
 
grade: 3
 
}
 
}
 
 
students = JSON.stringify(students); //將JSON轉爲字符串存到變量裏
 
console.log(students);
 
localStorage.setItem("students",students);//將變量存到localStorage裏
 
 
 
var newStudents = localStorage.getItem("students");
 
newStudents = JSON.parse(students); //轉爲JSON
 
console.log(newStudents); // 打印出原先對象
相關文章
相關標籤/搜索