4

I am doing the codecademy's javascript tutorial and encountering the problem as following:

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");

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

friends[prop], it will print out the bill and steve object information.

I see the w3c tutorial say that two of the access method is right and I cannot figure out

what is the problem?

Thx in advance.

1
  • 2
    You'll need to use the bracket notation method when using variables with objects like that, so just use friends[prop] as friends.prop will never work. Commented Feb 24, 2013 at 19:17

1 Answer 1

2

The array notation ([prop]) is providing an additional level of indirection, a type of reflection.

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

If you try friends.prop, you're literally asking for it to look for a friend named "prop".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.