Roman P
Roman P

Reputation: 35

Using a parameter with a Javascript object?

Currently I can do:

function addStat() {
player.str = player.str + 1;
}

But I want to be able to use things other than just "str" with my player object. So I decided with doing something like this:

function addStat(stat) {
player.stat = player.stat + 1;
}

But that doesn't seem to work, iv'e tried looking up the syntax for using parameters but could not find anything similar to the way I need.

I learned about "this" but I can't get it to work with my function.

I thought this:

function addStat(thing, stat) {
thing.stat = thing.stat + 1;
statReset();
}

would work but I can see why it won't. I made sure the rest of my javascript and html work and when I add those functions nothing breaks, it just doesn't work.

Upvotes: 1

Views: 63

Answers (3)

ndugger
ndugger

Reputation: 7531

When assigning properties with a variable, you need to use bracket notation, as opposed to dot notation. This, then, looks like:

function addStat(stat) {
    (stat in player) ? ++player[stat] : player[stat] = 1;
}

Due to comments (that I disagree with), I figured I should mention that since you are attempting to modify a property that may not exist, you should also add a safety check to see if you can modify it.

Otherwise you will be modifying undefined, and that will cause undesired output..

Upvotes: 4

CupawnTae
CupawnTae

Reputation: 14600

In javascript, the syntax

object.key

is equivalent to

object["key"]

So your thing.stat is equivalent to thing["stat"], i.e. the key is the literal string "stat" when what you really want is to use the value referenced by the parameter stat as the key:

thing[stat] = thing[stat] + 1;

Upvotes: 0

LS_ᴅᴇᴠ
LS_ᴅᴇᴠ

Reputation: 11181

You can access properties with []:

function addStat(prop) {
    player[prop] = player[prop] + 1;
}

so calling addStat("stat") will actually set player.stat.

Upvotes: 0

Related Questions