简体   繁体   English

localStorage array.push

[英]localStorage array.push

Could someone tell me how to push elements into an array in localStorage?有人可以告诉我如何将元素推送到 localStorage 中的数组中吗?

My code:我的代码:

 (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>

General approach:一般的做法:

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

let new_data = old_data.push(some_new_data)

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

The problem you are hitting is that data stored in localStorage has to be a string.您遇到的问题是存储在localStorage中的数据必须是字符串。 You'll have to parse/stringify before settting/getting anything from local storage.在从本地存储设置/获取任何内容之前,您必须解析/字符串化。 If you didn't want to work with strings, you may find something like IndexedDB API如果您不想使用字符串,您可能会发现类似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'));

Here is an example of using IndexedDB API from the docs这是使用文档中的 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);
    });
  };
};

There are also other solutions out there like PouchDB depending on your needs根据您的需要,还有其他解决方案,例如PouchDB

I would do the following assuming that your data is not a multiDimensional array.假设您的数据不是多维数组,我会执行以下操作。

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

Say for example you have an array.例如说你有一个数组。 This is how you can store it in the local storage.这就是您可以将其存储在本地存储中的方式。

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

Now to push any data into the local storage array you have to override by the new data like bellow现在要将任何数据推送到本地存储阵列中,您必须用新数据覆盖,如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM