我正在尝试在 localStorage 中保存字符串数组。这是我的代码:
export const saveComment = (state) => {
try {
const commentExisting = localStorage.getItem("comment");
const comment = commentExisting ? commentExisting.split(", ") : [];
comment.push(state);
localStorage.setItem("comment", JSON.stringify(comment));
} catch (err) {
console.log(err);
}
};
添加几个值后,我得到很多转义字符:
["[\"[\\\"Some comment\\\"]\",\"another one\"]","one more comment"]
我希望它是这样的:[“一些评论”,“另一条评论”,“还有一条评论”]
我的代码有什么问题吗?
最佳答案
您需要对 localStorage.getItem('comment')
的结果进行JSON.parse
。这会将其转回一个可以直接使用的数组,而不是用逗号分割。
const saveComment = (state) => {
try {
const commentExisting = localStorage.getItem("comment");
const comment = commentExisting ? JSON.parse(commentExisting) : [];
comment.push(state);
localStorage.setItem("comment", JSON.stringify(comment));
} catch (err) {
console.log(err);
}
};
关于javascript - 在 localStorage 中添加不带转义字符的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63162939/