javascript - 如何将转换后的字符串转换回数组?

标签 javascript arrays string p5.js

据我所知,你只能将字符串保存到本地存储。所以,我不得不写一个函数来保存数组。如果我调用 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:

在页面加载时:

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));

关于javascript - 如何将转换后的字符串转换回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52017430/

相关文章:

javascript - Modernizr 减慢了表排序器的速度

javascript - 在 IE8 中非常奇怪的事情。定义的变量被识别为 'undefined'

javascript - 如何从嵌套的 json 数组中提取数据?

sql - PostgreSQL 检查匹配正则表达式的表数

Java 字符串缓冲区 - 如何删除

javascript - 使用身份服务器 4 匿名访问 SignalR hub

javascript - 使用 MVC/Backbone.js 实现复合模式

java - 给定一个整数数组(长度为 n),使用 Java 中的递归查找并返回输入数组的所有子集

python - 使用 python 在移动区间上查找最大值(和最小值)

c++ - string::erase(0) 在空字符串上?