Насколько я знаю, вы можете сохранять только строки в локальном хранилище.Итак, мне пришлось написать функцию, чтобы я мог сохранять массивы.Если я позвоню 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.
Не так много, но это насколько я получил.Любая помощь приветствуется.