我正在开发一款使用ES 6 JavaScript的应用。这个应用程序有一个游戏列表。每个游戏都有一个ID。对象定义如下:
let game1 = { id:'XVF/328', name:'Checkers', publisher:'ABC games' };
let game2 = { id:'FTY/294', name:'Chess', publisher:'Infinity Fun' };
let game3 = { id:'QPG/72Z', name:'Backgammon', publisher:'Max Fun' };
我有一个如下所示的数组:
let games = [];
我试图了解如何填充此数组以便快速访问。我没有,我会得到一个ID,比如' FTY / 294'。我试图了解如何设置游戏阵列,以便我可以执行以下操作:
let selectedGame = games['FTY/294'].
如何在JavaScript中执行此操作?
谢谢!
答案 0 :(得分:5)
在javascript中,对象的行为与Java / C#中的HashTable
或Dictionary
非常相似。您可以在键下使用商店值,并使用该键稍后检索该值。
如果您使用的是对象而不是数组,那么您将获得key->值访问权。
let games = {};
games['XVF/328'] = { id:'XVF/328', name:'Checkers', publisher:'ABC games' };
games['FTY/294'] = { id:'FTY/294', name:'Chess', publisher:'Infinity Fun' };
如果您需要遍历所有游戏,可以使用Object.keys(games)
检索所有键的列表,然后使用它来迭代您的对象。
Object.keys(games).forEach(x => {
var game = games[x];
// do something with game
});
在ES6中,您还可以选择使用Map,它可以为您提供关联数组的优势(如上所述),但增加了可迭代支持。
var games = new Map();
games.set('XVF/328', { id:'XVF/328', name:'Checkers', publisher:'ABC games' });
// ....etc
for (let [id, game] of games) {
// do something with the game
}
答案 1 :(得分:2)
您可能需要考虑using an object as an associative array,其功能类似于字典(即传入密钥并返回值):
// Define your object
let games = {};
// Add each game here
games['XVF/328'] = { name:'Checkers', publisher:'ABC games' };
games['FTY/294'] = { name:'Chess', publisher:'Infinity Fun' };
games['QPG/72Z'] = { name:'Backgammon', publisher:'Max Fun' };
然后通过以下方式检索您正在寻找的游戏:
let selectedGame = games[id]; // where id is something like "XVF/328"
答案 2 :(得分:0)
您可以将id用作新对象中的键:
games = {};
games[game1.id] = game1;
games[game2.id] = game2;
games[game3.id] = game3;
希望这有帮助。
game1 = { id:'XVF/328', name:'Checkers', publisher:'ABC games' };
game2 = { id:'FTY/294', name:'Chess', publisher:'Infinity Fun' };
game3 = { id:'QPG/72Z', name:'Backgammon', publisher:'Max Fun' };
games = {};
games[game1.id] = game1;
games[game2.id] = game2;
games[game3.id] = game3;
console.log(games);
答案 3 :(得分:0)
如果您使用的是ES6,那么您一定要使用Maps
const games = new Map(); // or let
games.set('XVF/328', { id:'XVF/328', name:'Checkers', publisher:'ABC games' })
games.set('FTY/294', { id:'FTY/294', name:'Chess', publisher:'Infinity Fun' };
games.set('QPG/72Z', { id:'QPG/72Z', name:'Backgammon', publisher:'Max Fun' };
let game = games.get('FTY/294');