2016-02-20 40 views
1

我目前正在編寫一個函數來預先載入一個小遊戲所使用的所有圖像以在數組上繪製。目前我在兩個不同的數組中存儲源的路徑來解決這個問題,但是如果有一個數組可以使用數字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(); 
} 
+1

你有沒有研究過創建某種[dictionary/hash table](http://stackoverflow.com/questions/1208222/how-do-i-implement-a-dictionary-or-hashtable-in-javascript)或二維數組? – freddiev4

+0

或者你可以有一個對象數組,每個對象有一個鍵和一個值,如:'[{key:0,val:'bla'},{key:1,val:'blabla'}]' – nem035

+0

在JavaScript中,對象鍵可以是幾乎任何東西。所以,你可以逃避:'var myobj = {'snakehead':somevalue};'要訪問,使用數組表示法:'myobj ['snakehad']'。基本上,每個數組項都成爲一個對象屬性(例如'{'snakehead':val1,'snaketail':val2}')。 – jbarreiros

回答

3

絕對!

在JS中,您可以創建任何數據類型的數組。你也可以訪問對象。所以我們結合這些。

var obj = { 
    name: 'a test name', 
    value: 1 
} 

var array = [obj]; 

array[0].name; // == 'a test name' 
array[0].value; // == 1 

var anotherObj = { 
    name: 'another name', 
    value: 7 
} 

array.push(anotherObj); 


array[1].name; // == 'another name' 
array[1].value; // == 7 

讀你的問題更具體,我看你也希望有一個可以從值拉get方法。這有點棘手。

提供的其他答案將做到這一點,但將數據存儲在對象(不是數組)中的兩個單獨位置,也丟失了數組原型。

爲了更好的解決Array類的類型,我們只需要利用Array.filter!

array.filter(function(item) { return item.name === 'another name' }) 

這將爲您提供滿足您指定的回調函數中提供力所能及的標準元素的子數組。在這種情況下,使用上面的數組,它會傳回一個包含一個元素的數組; anotherObj

+0

是的,javascript對我來說有點生疏......但當然! –

+0

剛開始認爲我知道面向對象的編程如何能夠使我受益,那麼您就是這樣做的!看起來不錯,會盡力實施。 – Selbyggen

+0

在閱讀完您的用例之後再提供一些額外的信息。希望能幫助到你。 – gravityplanx

0

如果你想雙方訪問,使用對象

var arr = {} 
arr[1] = arr['myKey'] = 'myValue' 

然後你就可以通過這兩個號碼,並通過鍵訪問它們。

相關問題