存数据:sessionStorageSet
-
// 存数据
-
export
const sessionStorageSet =
(name, obj) => {
-
if (
typeof obj ===
'undefined') {
-
return
false
-
}
-
// obj为undefined或null或空字符串不能存储,布尔值可存储,但取时为字符串
-
if(!obj && (
typeof obj ===
'undefined' ||
typeof obj ===
'object' ||
typeof obj ===
'string')) {
-
return
false
-
}
-
let saveStr =
''
-
if (
typeof obj ===
'object') {
-
saveStr =
JSON.stringify(obj)
-
}
else {
-
saveStr = obj
-
}
-
sessionStorage.setItem(name, saveStr)
-
return
true
-
}
-
取数据:sessionStorageGet
-
// 取数据
-
export
const sessionStorageGet =
(name) => {
-
if (
typeof name !==
'string') {
-
return
-
}
-
var savedStr = sessionStorage.getItem(name)
-
// 非法值返回,包括undefined、null、空字符串
-
if (!savedStr) {
-
return
-
}
-
var result
-
if ((savedStr.indexOf(
'"') <
0 && savedStr.indexOf(
'\'') <
0) || savedStr.indexOf(
':') <
0) {
-
return savedStr
-
}
-
try {
-
result =
JSON.parse(savedStr)
-
return result
-
}
catch (e) {
-
return savedStr
-
}
-
}
删除某项缓存数据:sessionStorageRemove
-
export
const sessionStorageRemove =
(name) => {
-
if (
typeof name !==
'string') {
-
return
-
}
-
sessionStorage.removeItem(name)
-
}
清除本地所有存储数据:sessionStorageClear
-
export
const sessionStorageClear =
(name) => {
-
if (name) {
-
return
-
}
-
sessionStorage.clear()
-
}