javascript - 如何将转换后的字符串转换回数组?
问题描述
据我所知,您只能将字符串保存到本地存储。所以,我必须编写一个函数来保存数组。如果我打电话console.log(fixA(["string1", [5, [false]], "string2"]));
,我会得到"'string1',[5,[false]],'string2'"
. 这里是:
function fixA(array) {
var toreturn = "";
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'object') {
toreturn += "[" + fixA(array[i]) + "]";
} else {
if (typeof array[i] === 'string') {
toreturn += "'" + array[i] + "'";
} else {
toreturn += array[i];
}
}
if (i < array.length - 1) {
toreturn += ",";
}
}
return toreturn;
}
console.log(fixA(["string1", [5, [false]], "string2"]));
现在的问题是我不知道如何将其转换回来。我尝试了一些事情,但总是卡在如何将数组转换回来。这基本上是我尝试过的:
function fixS(string) {
var toreturn = [];
var temp = string.split(",");
for (var i = 0; i < temp.length; i++) {
// I could run a check here to see if temp[i] starts with "[", but I'm not sure how to tell where the array ends.
// If it is an array, then I'd need to pass everything inside of the array back into fixS, making it recursive.
// The times I tried to do those two things above, I ran into the issue that the commas inside of the sub arrays also split everything, which I don't want (as the recursive function will deal with that).
toreturn.push(temp[i]);
}
return toreturn;
}
console.log(fixS("'string1',[5,[false]],'string2'"));
// This also doesn't return numbers as numbers or booleans as booleans.
那里不多,但据我所知。任何帮助表示赞赏。
解决方案
除非您有无法用 JSON 表示的内容(您的示例可以),否则不要使用自己的定制解决方案,而是使用 JSON:
在页面加载时:
var data = JSON.parse(localStorage.getItem("data") || "null");
if (!data) {
// There wasn't any, initialize
}
或者
var data = JSON.parse(localStorage.getItem("data") || "{}");
...如果您想要一个空白对象,如果本地存储中没有任何内容。
保存数据时:
localStorage.setItem("data", JSON.stringify(data));
推荐阅读
- install4j - 静默安装期间的“java.lang.InternalError:意外的 CryptoAPI 失败生成种子”
- sql - 如何使用 LEFT JOIN 仅检索不匹配的结果?
- mongodb - 事务中的猫鼬 findOne():未捕获的类型错误:无法读取未定义的属性“$elemMatch”
- node.js - 使用 DynamoDB 时,我可以在同一个主键下有多个条目吗?
- sql - 使用特殊字符更新查询作为 oracle 表中的数据
- jquery - addClass 后无法定位类
- node.js - 本地主机上的客户端和服务器的自签名证书客户端身份验证
- sql - 如何在使用外键引用自身的表中提取根元素?(环形 ?)
- ubuntu - 仅使用 Python 3 安装 ROS 旋律且不会弄乱系统库?
- javascript - P5.JS .show() 不是函数,为什么?