Using a period to access an object, but undefined

I am doing a javascript codecademy tutorial and run into a problem like this:

  var friends = {};
 friends.bill = {
   firstName: "Bill",
   lastName: "Gates",
   number: "(206) 555-5555",
   address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
 };
 friends.steve = {
   firstName: "Steve",
   lastName: "Jobs",
   number: "(408) 555-5555",
   address: ['1 Infinite Loop', 'Cupertino', 'CA', '95014']
 };
 var list = function (obj) {
     for (var prop in obj) {
         console.log (prop);
     }
 };
 var search = function (name) {
   for (var prop in friends) { 
         console.log (prop);
         console.log (friends.prop); // friends [prop] will print out 

   }


 };
 list (friends);
 search ("Steve");

console.log (friends.prop) will print undefined, but if I changed it to

friends [prop], it prints out information about the account and the text of the object.

I see that the w3c tutorial says that the two access methods are right and I cannot understand

what is the problem?

thanks in advance.

+4
source share
1 answer

An array designation ( [prop] ) provides an additional level of indirection, a type of reflection.

So friends.bill and friends["bill"] will be identical. But if you want to do something like var prop = 'bill' , then the only way to use it is friends[prop] .

If you try friends.prop , you literally ask him to find a friend named "prop".

+2
source

All Articles