我目前正在编写一个函数来预先载入一个小游戏所使用的所有图像以在数组上绘制。目前我在两个不同的数组中存储源的路径来解决这个问题,但是如果有一个数组可以使用数字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