javascript - 将大量字符串存储到 IndexedDB 中

标签 javascript arrays indexeddb

我有一个名为 newCombs 的巨大数组,当我调用 store.put(game) 时,选项卡会变成白色,并在 Chrome 任务管理器中消失。基本上该过程只是停止并且无法存储数组

var trans = this.db.transaction('Games', 'readwrite');
var store = trans.objectStore('Games');
store.get(new Date().toLocaleDateString() + ' ' + prize.value).onsuccess = function() {
  var game = this.result;
  game.combs = game.combs.concat(newCombs); //I'm appending to the game.combs array which is empty when I first run it (when it also crashes)
  store.put(game);
}
trans.oncomplete = function(evt) {
  arrLength = 0;
  newCombs = [];
}

这就是 game 等于:

game = {
   name: new Date().toLocaleDateString() + ' ' + prize.value,
   date: new Date().toLocaleDateString(),
   prize: prize.value,
   playerData: [...],
   points: {...}
}

上面的部分是对象的方法,因此 this 不是窗口对象,一切正常,直到代码到达以下行:store.put(game); 页面崩溃了。

最佳答案

正如 @paldepind 建议的那样,您正在更改 onsuccess 事件处理程序中的范围并忽略自定义对象。

解决这个问题的一种方法是在定义匿名回调函数之前,利用闭包并将 this 分配给局部变量:

var trans = this.db.transaction('Games', 'readwrite');
var store = trans.objectStore('Games');
var that = this;
store.get(new Date().toLocaleDateString() + ' ' + prize.value).onsuccess =     function() {
  var game = that.result;
  game.combs = game.combs.concat(newCombs); 
  store.put(game);
}
trans.oncomplete = function(evt) {
  arrLength = 0;
  newCombs = [];
}

关于javascript - 将大量字符串存储到 IndexedDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468583/

相关文章:

php - 如何获取一个类的所有公共(public)属性作为json?

javascript - 游标.update(val) 或 put(val, id)?

google-chrome - 在 IndexedDB 和文件系统之间本地存储 chrome 应用程序数据的最佳选择是什么?

javascript - 进行同步 JavaScript 调用的技巧

javascript - 如何在js数据表中查找和更新特定记录

javascript - JS 函数和 IIFE

php - 在循环中设置键和值

java - 从元素集中删除对象

javascript - Apollo 订阅 - 处理 WS 与 subscribeToMore 断开连接

javascript - Chrome 打包应用程序中的 https 请求(javascript)