monny
monny

Reputation: 1

Passing an object key to a function

There's a lot I don't quite understand about javascript, so I may be misunderstanding something basic about objects. I understand there is a difference between . and [], so that's presumably part of the problem, but I don't know how to resolve this.

var game = {
    playerlvl:1
}

function displayinfo(name){
    var info = document.getElementById( name );
    info.innerHTML = game[name];
}

displayinfo(playerlvl);

I want the function to result in the same as:

document.getElementById("playerlvl").innerHTML = game.playerlvl;

Upvotes: 0

Views: 80

Answers (2)

Manish Kumar
Manish Kumar

Reputation: 10502

Here i solved for you http://jsfiddle.net/xt7utnhz/

You was just missing displayinfo("playerlvl");

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074465

All you're missing in quotes:

displayinfo("playerlvl");

In JavaScript, you can access properties using dot notation and a literal property name (game.playerlvl), or using brackets notation and a string property name (game["playerlvl"]). (In ES6, brackets notation will also support Symbols.) The string (or Symbol) in the brackets can be the result of any expression, including a variable/argument lookup. So game[name] works, if name's value is a string or can reasonably be turned into one.

You're already correctly using brackets notation in displayinfo, you just need to pass it a string rather than using a literal. Your code using a literal is trying to use a variable called playerlvl on the displayinfo(playerlvl) line, which doesn't exist, and so gets a ReferenceError.

Upvotes: 2

Related Questions