1

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.

1

3 Answers 3

4

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..

Sign up to request clarification or add additional context in comments.

10 Comments

@Andy -- while your comment is valid, it has nothing to do with the current question at hand.
@Jamiec it works for setting new properties, it doesn't work for modifying properties that don't yet exist.
@Alnitak - How can you modify something that doesnt exist?
@NickDugger, I disagree. The OP is moving from using specific keys to possibly passing in a parameter for a key that doesn't yet exist. I think that's worth mentioning.
@NickDugger, if you disagree with it you shouldn't add it to your answer. That's just weird, man.
|
0

You can access properties with []:

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

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

3 Comments

No, it will add 1 to player.stat on the assumption that the key exists.
OP post also assumes this. There is no checking in original code.
The OP doesn't assume this because he might decide to pass in a parameter for a keys that doesn't exist yet. I think that's worth mentioning.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.