localstorage中的javascript数组

时间:2016-11-15 12:50:25

标签: javascript jquery arrays

我有这段代码,用输入框为数组添加值。我想在localStorage中保存该数组,并在另一页上显示该数组的内容。

<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
window.onload = function() {
    var inputArray = [];
    var input = document.getElementById('inputbox');
    var screen = document.getElementById('screen');

    document.getElementById('submit').onclick = function () {
        inputArray.push(input.value);
        screen.innerHTML = input.value;
    };

    document.getElementById('display').onclick = function () {
        screen.innerHTML = inputArray
    };
} 

3 个答案:

答案 0 :(得分:2)

您没有在localStorage中保留数据。由于localStorage只保留字符串数据,因此您可以在存储时stringify和阅读时parse

 window.onload = function() {
     var inputArray = [];

     //Check if data is persisted in localStorge then load in the array
     var str = localStorage.getItem('nyArray')
     if (str) {
         inputArray = JSON.parse(str);
     }

     var input = document.getElementById('inputbox');
     var screen = document.getElementById('screen');

     document.getElementById('submit').onclick = function() {
         inputArray.push(input.value);
         screen.innerHTML = input.value;

         //Store stringifyed string
         localStorage.setItem('nyArray', JSON.stringify(inputArray))
     };

     document.getElementById('display').onclick = function() {
         screen.innerHTML = inputArray
     };
 }

答案 1 :(得分:1)

您可以stringify您的阵列,然后将其保存在localStorage中。如有需要,请阅读并parse将其恢复为数组。

var originalArr = ["V", "A"];
var strArr = JSON.stringify(originalArr);

// to save your array
localStorage.setItem("YOUR_KEY",strArr);

// to read from localstorage
var yourOriginalArray = localStorage.getItem("YOUR_KEY");

答案 2 :(得分:-2)

使用全局变量见下文

window.savedarray = inputArray

现在您可以访问其他页面中的savedarray