localStorage用法小總結
阿新 • • 發佈:2017-11-27
打印 val scrip span ttr aso comm head com
console.log(students); localStorage.setItem("students",students);//將變量存到localStorage裏
var newStudents = localStorage.getItem("students");
newStudents = JSON.parse(students); //轉為JSON
console.log(newStudents); // 打印出原先對象
API如下表所示
名稱 | 作用 |
---|---|
clear | 清空localStorage上存儲的數據 |
getItem | 讀取數據 |
hasOwnProperty | 檢查localStorage上是否保存了變量x,需要傳入x |
key | 讀取第i個數據的名字或稱為鍵值(從0開始計數) |
length | localStorage存儲變量的個數 |
propertyIsEnumerable | 用來檢測屬性是否屬於某個對象的 |
removeItem | 刪除某個具體變量 |
setItem | 存儲數據 |
toLocaleString | 將(數組)轉為本地字符串 |
valueOf | 獲取所有存儲的數據 |
清空localStorage
localStorage.clear() // undefined
存儲數據
localStorage.setItem("name","caibin") //存儲名字為name值為caibin的變量
讀取數據
localStorage.getItem("name") //caibin,讀取保存在localStorage對象裏名為name的變量的值
localStorage.valueOf() //讀取存儲在localStorage上的所有數據
刪除某個變量
localStorage.removeItem("name"); //undefined
檢查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轉為字符串存到變量裏localStorage用法小總結