2016-02-20 30 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' 

然后你就可以通过这两个号码,并通过键访问它们。

相关问题