是否可以在数组中同时存储值的数字和名称
Is it possible to store both a number and name for a value in an array?
我目前正在编写一个函数来预加载小游戏用于在数组上绘制的所有图像。目前,我将源的路径存储在两个不同的数组中以解决此问题,但是在从中获取值时,是否有可能拥有一个可以同时使用数字 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'
然后,您可以按数字和密钥访问它们。
相关文章:
- 使用全局变量来存储数字(JavaScript)
- 将数字转换为16位浮点(存储为字节)并返回
- 将数字存储在数组中会混淆如何根据值而不是索引来操作这些项目
- 如何查找和替换包含数字的名称并将该数字存储在变量中
- 是否可以在数组中同时存储值的数字和名称
- 在 JavaScript 中将小数字合并为一个是个好主意吗?(作为存储优化解决方案)
- 将数字分组到大小为 X 的最少数量的存储桶中
- 从字符串中提取数字并将其存储在数组Javascript中
- 以何种格式记录/存储数字数据以供进一步的JavaScript处理
- Regex/Javascript函数将价格存储为基于美分的数字
- 生成和存储电子(数字)签名
- 存储和增加数字,即使在刷新页面后
- 不能存储非数字字符
- 使用.replace()在HTML5数据属性上存储jQuery $.data()检索到的数字时未捕获的TypeError
- 将不同的数字存储到数组中
- 如何对本地存储中的嵌套键进行数字排序
- 存储一个随机生成的数字
- Javascript存储一个数字,以便以后与web存储一起使用
- 如何从字符串中提取数字并存储在数组中
- 如何在数组中存储的字符串中查找数字的和