function appendLocal(key, obj) {
if (obj == null) return;
var temp, tempStr = '';
try {
if (localStorage.getItem(key) == null) throw new Error('空或undefined')
temp = JSON.parse(localStorage.getItem(key));
} catch (err) {
// 当localStorage中没有对应key,或key对应内容为空、undefined,或parse出错时
temp = [];
}
temp = temp.map((item) => {
return JSON.stringify(item);
});
// 去重
if (temp.indexOf(JSON.stringify(obj)) === -1) temp.push(JSON.stringify(obj));
temp.forEach((item, index, arr) => {
arr.length === index + 1 ? tempStr += `${item}` : tempStr += `${item},`;
});
localStorage.setItem(key, `[${tempStr}]`);
}
网友评论