-1

I have an object, Player, which has different properties for different rounds for example round_1, round_2, .. , round_7. I would like to give them values depending on the integer, round value.

What i thought would work would be with a function:

//voor = round in Estonian
function valiVoor(player, r){
if (r == 1){
    return player.voor_1;
}
else if (r == 2){
    return player.voor_2;
}
else if (r == 3){
    return player.voor_3;
}
else if (r == 4){
    return player.voor_4;
}
else if (r == 5){
    return player.voor_5;
}
else if (r == 6){
    return player.voor_6;
}
else if (r == 7){
    return player.voor_7;
}
}

Although calling out function:

valiVoor(player_one,1) = "asd";

Will not change the property player_one.voor_1 = "asd". Should i work with arrays or is there any other option to resolve the issue?

shawwy
  • 122
  • 1
  • 12

3 Answers3

4

You could use the Bracket notation:

player['voor_' + r] = 'asd'; //Equivalent to player.voor_# where # is the number r

If you want to check if the property exists before assigning (otherwise if r goes crazy it takes your player object in its madness):

if(player.hasOwnProperty('voor_' + r)) {
  //Do stuff
}

See this MDN link for Object.prototype.hasOwnProperty.

Kyll
  • 7,036
  • 7
  • 41
  • 64
1
function valiVoor(player, r){
    return player['voor_'+r];
}

And a setter:

function setValiVoor(player, r, value){
    player['voor_'+r] = value;
}
Chris Charles
  • 4,406
  • 17
  • 31
0

You can also access Object properties with the squared brackets just like Arrays.

function getValiVoor(player, r){
    return player['voor_' + r];
}

If you want to assign a value, you could pass the value to the function:

function setValiVoor(player, r, val){
    player['voor_' + r] = val;
}
klein
  • 36
  • 2
  • 4