我目前正在使用我的初級編程類中的「最終項目」工作。因此,核心部分是能夠保存遊戲數據。在遊戲中,有4個陣列,每個陣列9個地方,代表遊戲中的庫存。庫存打印清單中的狹槽,該產品可在物品的圖像的一個是用於該項目的對象:嘗試使用localStorage在JavaScript中使用對象保存和加載數組時出現錯誤
this.inventory = {1: num[1], 2: num[30], 3: num[33], 4: num[9], 5: "empty", 6: "empty", 7: "empty", 8: "empty", 9: "empty"};
每個項目(例如NUM [1])具有屬性圖像配,和一個。數據屬性。 下一陣列被用來定義項目的量:
this.inventoryStack = {1: 1, 2: 7, 3: 99, 4: 5500, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0};
然後有一個用於圖像,後跟一個用於數據(數據被存儲在獨立的陣列):
this.images = {1: num[1].image, 2: num[30].image, 3: num[33].image, 4: num[9].image, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0};
this.data = {1: rods[0], 2: num[30].data, 3: num[33].data, 4: num[9].data, 5: 0 , 6: 0, 7: 0, 8: 0, 9: 0};
The result of these these arrays will look like this in the game:
我使用的localStorage的方法如下所示,首先保存數據,然後用單獨的鍵盤按壓還原:
this.save = function() {
if(keyState[77]) {
localStorage.setItem("inventorySave", JSON.stringify(this.inventory));
localStorage.setItem("stackSave", JSON.stringify(this.inventoryStack));
localStorage.setItem("imageSave", JSON.stringify(this.images));
localStorage.setItem("dataSave", JSON.stringify(this.data));
}
}
this.restore = function() {
if(keyState[78] && this.restorer == true) {
this.restorer = false;
}
if(this.restorer == false && this.restoreTick < 2) this.restoreTick++;
if(this.restoreTick == 1) for(var i in this.inventoryStack) this.inventoryStack[i] = 0;
if(this.restoreTick == 2) {
this.parser1 = JSON.parse(localStorage.getItem("inventorySave"));
this.parser2 = JSON.parse(localStorage.getItem("stackSave"));
this.parser3 = JSON.parse(localStorage.getItem("imageSave"));
this.parser4 = JSON.parse(localStorage.getItem("dataSave"));
for(var i in this.parser1) {
if(this.parser1[i] != "empty") {
this.inventory[i] = this.parser1[i];
this.inventoryStack[i] = this.parser2[i];
this.images[i] = this.parser3[i];
this.data[i] = this.parser4[i];
}
}
if(!keyState[78]) {
this.restoreTick = 0;
this.restorer = true;
}
}
}
但是,當我嘗試保存然後恢復時,出現此錯誤: 「Uncaught TypeError:無法執行'CanvasRenderingContext2D'上的'drawImage':提供的值不是'CSSImageValue或HTMLImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)'「
我想知道,這裏可能是什麼錯誤?這是我的第一個問題,所以對於任何錯誤的表述或描述都很抱歉!我曾經看過的話題其他問題,但他們不能幫我:(
簡單的把戲。 localStorage和sessionStorage都不能保存對象或數組,只能保存字符串。在添加JSON.stringify(對象)之前和JSON.parse在閱讀 – TypedSource
@TypedSource ...你讀過這個問題了嗎? OP正在那樣做。 – rgthree
哎呀,對不起,沒看過;) – TypedSource