是否可以在数组中同时存储值的数字和名称

Is it possible to store both a number and name for a value in an array?

本文关键字:数字 存储 数组 是否      更新时间:2023-09-26

我目前正在编写一个函数来预加载小游戏用于在数组上绘制的所有图像。目前,我将源的路径存储在两个不同的数组中以解决此问题,但是在从中获取值时,是否有可能拥有一个可以同时使用数字 i 或名称 n 的数组?这将有助于以后更容易使用该值作为我的图片的搜索,并且使用gameimage[153]作为源值看起来不是很整洁,我宁愿使用gameimage["蛇头"]

当前代码示例:

//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();
}

当然!

在 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 .

如果要同时访问两者,请使用对象

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

然后,您可以按数字和密钥访问它们。