0
var test={
  dha1:'Boolean',
  dha2:'Boolean',
  dha3:'Number',
  dha4:'String'
}

for(x in test){
  console.log(test.x);
}

Here i want my output as Boolean Boolean Number String

But its return undefined for all four properties

Liam
  • 27,717
  • 28
  • 128
  • 190
Dhairya Lakhera
  • 4,445
  • 3
  • 35
  • 62
  • "for all four properties"?? You're just retrieving one property only, and that doesn't exist. You need to use bracket notation here: `console.log(test[x])`. – Teemu Feb 18 '16 at 16:08
  • Ok thanks.. but why '.x' is not working here? – Dhairya Lakhera Feb 18 '16 at 16:13
  • Because .x is trying to output a property called x (literally test.x) which does not exit, not read a property called the **value** of x – Liam Feb 18 '16 at 16:14
  • Because `test.x` is literally `test.x`, `x` here isn't the variable `x`, it's just a property name. Bracket notation allows you to use strings as property names, or variables containing a string. – Teemu Feb 18 '16 at 16:15
  • Ah, there's the duplicate I was looking for.... – Liam Feb 18 '16 at 16:15
  • 1
    Also see [Dynamically access object property using variable](http://stackoverflow.com/q/4244896/218196) – Felix Kling Feb 18 '16 at 16:15
  • console.log(typeof(x)) is correct ? – Dhairya Lakhera Feb 18 '16 at 16:25

1 Answers1

3

Use test[x] instead of test.x.

var test={
  dha1:'Boolean',
  dha2:'Boolean',
  dha3:'Number',
  dha4:'String'
}

for(x in test){
  console.log(test[x]);
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28