类别 | 说明 |
---|---|
保存 | localStorage.setItem(key,value) |
获取 | localStorage.getItem(key) |
删除 | localStorage.removeItem(key) |
清空 | localStorage.clear() |
localStorage.setItem('str', 'male')
let str = localStorage.getItem('str') console.log(str);
localStorage.setItem('num', 2114)
let num = localStorage.getItem('num') console.log(num); //类型转换为数值型[蓝色] console.log(Number(num));
let arr = [1, 2, 3, 4, 5]; let res; console.log('before set: ', arr); localStorage.setItem('arr', arr) res = localStorage.getItem('arr') console.log('after get ', res);
localStorage.setItem('arr1', JSON.stringify(arr));
res = JSON.parse(localStorage.getItem('arr1')); console.log('解析获取:res:', res);
res = JSON.parse(localStorage.getItem('arr1')) || [];
let obj = { name: 'glc' } //使用JSON.stringify转换 localStorage.setItem('obj', JSON.stringify(obj)) // 使用JSON.parse解析 let obj1 = JSON.parse(localStorage.getItem('obj')) console.log(obj1);
obj1 = JSON.parse(localStorage.getItem('obj')) || {};