本地存储 array.push

localStorage array.push

有人能告诉我如何将元素推入 localStorage 中的数组吗?

我的代码:

  (localStorage.getItem('projects') === null) ? localStorage.setItem('projects', ['proj1', 'proj2', 'proj3']) : '';
  var ItemGet = localStorage.getItem('projects');
  function CreateObject() {
    console.log(ItemGet);
    var Serializable = JSON.parse(ItemGet);
    Serializable.push('proj4');
    console.log(ItemGet);
  }
<button onclick="CreateObject()">Add Object</button>

一般方法:

let old_data = JSON.parse(localStorage.getItem('projects'))

let new_data = old_data.push(some_new_data)

localStorage.setItem('projects',JSON.stringify(new_data))

您遇到的问题是 localStorage 中存储的数据必须是字符串。您必须先 parse/stringify settting/getting 本地存储中的任何内容。如果您不想使用字符串,您可能会发现类似 IndexedDB API

的内容
const stuff = [ 1, 2, 3 ];

// Stringify it before setting it
localStorage.setItem('stuff', JSON.stringify(stuff));

// Parse it after getting it
JSON.parse(localStorage.getItem('stuff'));

这里有一个使用 IndexedDB 的例子 API 从文档

const dbName = "the_name";

var request = indexedDB.open(dbName, 2);

request.onerror = function(event) {
  // Handle errors.
};
request.onupgradeneeded = function(event) {
  var db = event.target.result;

  // Create an objectStore to hold information about our customers. We're
  // going to use "ssn" as our key path because it's guaranteed to be
  // unique - or at least that's what I was told during the kickoff meeting.
  var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });

  // Create an index to search customers by name. We may have duplicates
  // so we can't use a unique index.
  objectStore.createIndex("name", "name", { unique: false });

  // Create an index to search customers by email. We want to ensure that
  // no two customers have the same email, so use a unique index.
  objectStore.createIndex("email", "email", { unique: true });

  // Use transaction oncomplete to make sure the objectStore creation is
  // finished before adding data into it.
  objectStore.transaction.oncomplete = function(event) {
    // Store values in the newly created objectStore.
    var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
    customerData.forEach(function(customer) {
      customerObjectStore.add(customer);
    });
  };
};

还有其他解决方案,例如 PouchDB,具体取决于您的需要

假设您的数据不是多维数组,我将执行以下操作。

(localStorage.getItem('projects') === null) ? localStorage.setItem('projects', 
JSON.stringify(['proj1', 'proj2', 'proj3'])) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
     var Serializable = JSON.parse(ItemGet);
     Serializable.push('proj4');
     localStorage.setItem('projects',JSON.stringify(Serializable));
}

比如说你有一个数组。这是将其存储在本地存储中的方法。

let my_array = [1, 2, 3, 4];
localStorage.setItem('local_val', JSON.stringify(my_array))

现在要将任何数据推送到本地存储阵列,您必须用下面的新数据覆盖

let oldArray = JSON.parse(localStorage.getItem('local_val'))
oldArray.push(1000)
localStorage.setItem('local_val', JSON.stringify(oldArray))