我有一个名为 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/