storageJs
Posted GHUIJS
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了storageJs相关的知识,希望对你有一定的参考价值。
/**
* @param {String} storageName 本地存储key
* @param {itemKey} itemKey 子存储对象key
* @param {Boolean} isLcoal 是否如是永久持续性存储,默认持续性存储
*/
const dataSave = function(storageName, itemKey, itemVal, isLcoal = true) {
const Obj = JSON.parse(localStorage.getItem(storageName))||{};
Obj[itemKey] = itemVal;
localStorage.setItem(storageName, JSON.stringify(Obj))
}
/**
* @param {Object} storageName 本地存储key
* @param {Boolean} isLcoal web存储类别,默认取lcoalStorage
*/
const dataGet = function(storageName, isLcoal = true) {
if (isLcoal) {
if (isJSON(localStorage.getItem(storageName))) {
return JSON.parse(localStorage.getItem(storageName));
} else {
return localStorage.getItem(storageName);
}
} else {
if (isJSON(localStorage.getItem(storageName))) {
return JSON.parse(sessionStorage.getItem(storageName));
} else {
return sessionStorage.getItem(storageName);
}
}
}
/**
* @param {Array} storageKeyArr web存储key数组列表
* @param {Boolean} isLcoal 删除持续性存储还是回话性存储
*/
const dataDel = function(storageKeyArr, isLcoal = true) {
if (isLcoal) {
storageKeyArr.forEach(item => {
localStorage.removeItem('item')
})
} else {
storageKeyArr.forEach(item => {
sessionStorage.removeItem('item')
})
}
}
/**
* @param {String} str 检测字符串是否符合JSON规范
*/
function isJSON(str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
if (typeof obj == 'object' && obj) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
}
export {
dataSave,
dataGet,
dataDel
}
以上是关于storageJs的主要内容,如果未能解决你的问题,请参考以下文章