我目前正在編寫一個函數來預先載入一個小遊戲所使用的所有圖像以在數組上繪製。目前我在兩個不同的數組中存儲源的路徑來解決這個問題,但是如果有一個數組可以使用數字i或名稱n從數組中獲得值時可以使用數組嗎?這將有助於稍後使用該值將其作爲搜索分配給我的圖片,並且使用gameimage [153]作爲源值看起來不太整齊,我寧願使用gameimage [「snakehead」]是否可以爲數組中的值存儲數字和名稱?
當前的代碼示例:
//add images to the gameimages array to be loaded before gamestart
//add the snake images
var gameimages = [];
gameimages.push("snake30px.png", "snake30pxdown.png", "snake30pxup.png","snake30pxauch.png");
var gameimagesnumber = gameimages.length;
//start the startGame() when all images in the gameimages array is loaded, to avoid albino snake and lack of stuff to crash into
//NOTE: This is kinda "hackish" as the images is just loaded to make sure it is cached in browser...
//they're not actually used, but seem to have the same effect :x
for(var i = 0; i < gameimagesnumber; i++){
console.log("Loading " + gameimages[i]);
var image = new Image();
image.onload = function(){
//add the image in gameimagesnames for easier use in the code when needed
gameimagesnames[this.src.substring(this.src.lastIndexOf("/") + 1,this.src.length - 4)] = this.src;
checkforgamestart();
};
image.src = "images/" + gameimages[i];
}
//checking for gamestart
function checkforgamestart(){
if(gameimagesnumber > 1) gameimagesnumber--;
else startGame();
}
你有沒有研究過創建某種[dictionary/hash table](http://stackoverflow.com/questions/1208222/how-do-i-implement-a-dictionary-or-hashtable-in-javascript)或二維數組? – freddiev4
或者你可以有一個對象數組,每個對象有一個鍵和一個值,如:'[{key:0,val:'bla'},{key:1,val:'blabla'}]' – nem035
在JavaScript中,對象鍵可以是幾乎任何東西。所以,你可以逃避:'var myobj = {'snakehead':somevalue};'要訪問,使用數組表示法:'myobj ['snakehad']'。基本上,每個數組項都成爲一個對象屬性(例如'{'snakehead':val1,'snaketail':val2}')。 – jbarreiros