1

Can anyone tell why this is code not working

 var person = {fname:"John", lname:"Doe", age:25}; 

 var text = "";
 var x;
 for (x in person) {
   text += person.x + " ";
 }
 document.getElementById("demo").innerHTML = text;

If the variable is

var person = {fname:"John", lname:"Doe", age:25, x:"male"};

and var x; is not needed.

then it will work right?

vicky
  • 167
  • 4
  • 16
  • It's not working, because there's no property named `x` in your object. Use bracket notation instead of dot notation here. – Teemu Feb 01 '19 at 20:10
  • 2
    It should be `person[x]` – adiga Feb 01 '19 at 20:10
  • 1
    Also: [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – adiga Feb 01 '19 at 20:12

1 Answers1

2

You need to take the key in bracket notation. You could take two versions of a property accessor:

object['key'] // bracket notation
object.key    // dot notation

Only the first version works with a variable. The value of the variable has to be the wanted key.

var person = { fname: "John", lname: "Doe", age: 25 },
    text = "",
    x;

for (x in person) {
    text += person[x] + " ";
}
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392