简体   繁体   English

最好将数组存储在localstorage或许多变量中?

[英]Better to store array in localstorage or many variables?

Take for example a case where I have thousands of students. 举个例子,我有成千上万的学生。

So I'd have an array of objects. 所以我有一个对象数组。

students = [

{ "name":"mickey", "id","1" },
{ "name":"donald", "id","2" }
{ "name":"goofy", "id","3" }
...

];

The way I currently save this into my localstorage is: 我目前将其保存到本地存储中的方式是:

localStorage.setItem('students', JSON.stringify(students));

And the way I retrieve this from the localstorage is: 我从localstorage中检索这个的方法是:

var data = localStorage.getItem('students');
students = JSON.parse(data);    

Now, whenever I make a change to a single student, I must save ALL the students to the localStorage. 现在,每当我对一个学生进行更改时,我必须将所有学生保存到localStorage。

students[0].name = "newname";
localStorage.setItem('students', JSON.stringify(students));

I was wondering if it'd be better instead of keeping an array, to maybe have thousands of variables 我想知道它是否更好而不是保持阵列,可能有数千个变量

localStorage.setItem('student1', JSON.stringify(students[0]));
localStorage.setItem('student2', JSON.stringify(students[1]));
localStorage.setItem('student3', JSON.stringify(students[2]));
...

That way a student can get saved individually without saving the rest? 这样,学生可以单独保存而不保存其余部分?

I'll potentially have many "students".. Thousands. 我可能会有很多“学生”......数以千计。 So which way is better, array or many variables inside the localstorage? 那么哪个方式更好,数组或很多变量在localstorage中?

Note: I know I should probably be using IndexedDB, but I need to use LocalStorage for now. 注意:我知道我应该使用IndexedDB,但我现在需要使用LocalStorage。 Thanks 谢谢

For your particular case it would probably be easier to store the students in one localStorage key and using JSON parse to reconstruct your object, add to it, then stringifying it again and it would be easier than splitting it up by each student to different keys. 对于您的特定情况,可能更容易将学生存储在一个localStorage键中,并使用JSON解析来重建您的对象,添加它,然后再次对其进行字符串化,这比将每个学生拆分为不同的键更容易。

If you don't have so many data layers that you really need a real local database like IndexedDB, a single key and a JSON string value is probably OK for your case. 如果你没有这么多数据层,你真的需要一个真正的本地数据库,如IndexedDB,单个键和一个JSON字符串值可能适合你的情况。

There is limitation for the size of local storage and older browsers won't support it. 本地存储的大小有限制,旧版浏览器不支持它。

It is better to store in an array for couple reasons: 由于几个原因,最好存储在数组中:

  • Can use loops to process them 可以使用循环来处理它们
  • No JSON needed 不需要JSON
  • Always growable 永远可以成长

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

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