-2

I want alert object key name and its value. But it is not working.

$(function() {
    var james =  {first: '1,2,3', second: '4,5,6' } 
    $('a').click(function(){
        alert(james[first]) 
    })
})
VisioN
  • 143,310
  • 32
  • 282
  • 281
Jitender Chand
  • 93
  • 2
  • 3
  • 13

2 Answers2

5

You should correctly use either square bracket notation:

alert(james["first"])

or dot notation:

alert(james.first)

to access elements in objects.

Useful reference:

If you need to display all items in the object use for loop with in keyword:

for (var key in james) {
    // key          -- for key
    // james[key]   -- for value
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

you can use foreach to read all property :

for (var key in james) {
  alert(key);
}
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110