最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Append to array in localForage - Stack Overflow

programmeradmin4浏览0评论

I am using localForage to store some data on a website to make it offline.

I would like to have one key and append to the value / array.

So far I can only figure how to retrieve the entire key/value from storage, then append and set the entire key/value again. This seems very wasteful and might be problematic when the key/value gets larger.

var obj = ...
localforage.getItem('documents', function(err, value) {
  value.push(obj);
  localforage.setItem('documents', value);
}

Is there not a more efficient way of doing this? and how big would the key/value have to be to notice performance issues.

I am using localForage to store some data on a website to make it offline.

I would like to have one key and append to the value / array.

So far I can only figure how to retrieve the entire key/value from storage, then append and set the entire key/value again. This seems very wasteful and might be problematic when the key/value gets larger.

var obj = ...
localforage.getItem('documents', function(err, value) {
  value.push(obj);
  localforage.setItem('documents', value);
}

Is there not a more efficient way of doing this? and how big would the key/value have to be to notice performance issues.

Share asked Dec 29, 2014 at 11:58 Karl StulikKarl Stulik 9901 gold badge13 silver badges27 bronze badges 1
  • 3 I don’t think that is possible. But you could make a key system with keys like this key-1, key-2, and so on. – NatureShade Commented Dec 29, 2014 at 13:21
Add a ment  | 

1 Answer 1

Reset to default 7

I realize this is an old question, but thought I would provide some info. Per NatureShade's point, you can't edit the value in the localForage table, you can only pull the item, and set it. What I typically do for frequently changing variables/objects when using localForage is to have a global variable set for that item. When making changes I just update the global variable and then update the item in storage. The nice thing about this is you only have to worry about setting the localForage key/value, and don't have to mess with the asynchronous aspect as much. You also have a variable that you can always reference for this info as well, so you don't have to use .getItem all the time to access it. Having a global variable may not be the best practice, but it is an option.

var globalObject;
localforage.getItem('documents', function(err, value){
    globalObject = value;
}

var obj = ...;
globalObject.push(obj);
localforage.setItem('documents', globalObject);

var obj2 = ...;
globalObject.push(obj2);    
localforage.setItem('documents', globalObject);   
发布评论

评论列表(0)

  1. 暂无评论