Javascript Data Structures
How can I store player names and scores in a way that is easy to set, retrieve and update? Arrays, objects etc? What are the pro's and con's? Which is more e开发者_如何学Goxtensible?
I was thinking something like
Players {
[Dan : 500]
[Jess: 600]
[Elvis: 56]
}
Key-value stores in Javascript are objects:
var players = {
Dan : 500,
Jess : 600,
Elvis : 56
};
players.Dan = 300;
alert(players.Jess);
var Players = {};
// adding new player.
Players["Dan"] = 0;
// push score
Players.Dan += 10;
Objects have an advantage over key-value pairs in that they are extensible. You can store more attrbutes
http://www.w3schools.com/js/js_objects.asp
Objects would serve your purpose :
eg:
var players = { "Dan" : 500 , "Jess" : 600 , "Elvis" : 56 }
You can easily access values using key.
eg
alert(players["Dan"]);
see this example : http://jsfiddle.net/PQxHM/
精彩评论