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

时间:2018-08-25 12:42:25

标签: 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.

那里不多,但据我所知。任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:3)

除非您有自己的定制解决方案,否则除非使用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));

答案 1 :(得分:1)

正如David所说的,JSON.stringify()JSON.parse();

您可以使用这些方法:

function save_to_storage(id, anything){
    localStorage.setItem(id, JSON.stringify(anything));
}
function load_from_storage(id){
    return JSON.parse(localStorage.getItem(id));
}

答案 2 :(得分:0)

可以通过JSON.stringify和JSON.parse函数来实现。 让我借助代码片段进行探索。

var original_arr = ["string1", [5, [false]], "string2"];  // array
// Converting this array into string
var converted_str = JSON.stringify(original_arr); // converted into string
// Converting this string back to array
var new_arr = JSON.parse(converted_str );  // back to array

答案 3 :(得分:0)

其他答案已经涵盖了它,但是请注意,P5.js还提供了直接工作,保存和加载JSON的功能。

看看the reference中的saveJSON()loadJSON()函数。