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;
All you're missing in quotes:
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 supportSymbol
s.) The string (orSymbol
) in the brackets can be the result of any expression, including a variable/argument lookup. Sogame[name]
works, ifname
'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 calledplayerlvl
on thedisplayinfo(playerlvl)
line, which doesn't exist, and so gets aReferenceError
.