当前位置: 首页 > 工具软件 > Storage.js > 使用案例 >

storageJs

鲜于勇
2023-12-01
/**
 * @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
}

 类似资料:

相关阅读

相关文章

相关问答