开发者

Dynamically adding members to a javascript object

开发者 https://www.devze.com 2022-12-22 12:16 出处:网络
I\'m working on a scoring script for contract bridge, just for giggles. I\'m storing the game as an object:

I'm working on a scoring script for contract bridge, just for giggles. I'm storing the game as an object:

var game = {
    team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") }, 
    team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
}

function deal(bid){
    console.log("The bid was " + bid);
    game.hand = {"bid" : bid , "made" : undefined};
    score();
}

So what I'd like to do though, better than this, is to keep a history of the games played this session. I'd like to, in pseudocode, do something like this:

game.(hand + (hand.length+1))

or something kind of like that; basically auto-increment a certain object within an object开发者_运维百科. I'm not so sure an array would would here, but perhaps? I'm open to suggestions/bettering of my code.

PS - I'd prefer to do this in javascript, not jQuery, Prototype, Dojo, MooTools... or any other library. Thanks!

EDIT

Sorry, let me clarify: The result after playing 3 hands or so would be an object like this:

var game = {
    team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") }, 
    team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
    hand1 : { bid : 2 , made : 2 } ,
    hand2 : { bid : 1 , made : 4 } ,
    hand3 : { bid : 3 , made : 1 } ,
    hand4 : { bid : 2 , //and made hasn't been set yet because we're mid-hand

}


Given your pseudocode, you can do the following:

 game[hand + (hand.length+1)]

i.e. game["prop"] == game.prop - both provide access to the same property.


Old question, I see but I have a need to do something similar. I'd vote up the answer but I'm not allowed.

It appears the fastest way to do this is to access the object like a hash / associative array.

var d = {};
var z = "hand";
d[z+1] = "foo";

console.log(d.hand1);

Test this out in firebug. Seems to work pretty well. JS does not seem to have an php equivalent to force resolution of the variables as in the curley braces around an expression.

d->{z+1} = "foo";  // can't find anything like this in JS.

Hope that helps,

0

精彩评论

暂无评论...
验证码 换一张
取 消