1

When iterate through an object, reference value by using obj.key all get "undefined" while obj[key] works fine. They are supposed to be equivalent aren't they? Am I missing something?

jsfiddle link: http://jsfiddle.net/nLLcawcn/4/

function iterateObj(obj, callback) {
    if (obj == null || typeof obj != "object") {
        return;
    }
    for (var key in obj) {
        // callback(key, obj[key]);
        console.log("obj.key--->" + obj.key);
        console.log("obj[key]--->" + obj[key]);
        // callback(key, obj.key);
    }

}

var sample = {
    start: "bar",
    notes: [{
        location: "somewhere"
    }, {
        time: "someday"
    }],
    anotherobj: {
        another: "1",
        another1: "3",
        another2: "2"
    },
    end: "foo"
}
iterateObj(sample, function (key, value) {
    // console.log("key: " + key+ ", " + "value: "+ value);
})
Alan
  • 596
  • 5
  • 18
  • I have made a little example for you: http://jsbin.com/xefinokerowi/1/edit?js,console –  Oct 17 '14 at 15:24

1 Answers1

1

No they're not identical. You need to use bracket notation when you're doing a property lookup on the object and the property you're looking up, or in this example 'key', is a placeholder for something else. For example, 'key' in your for in loop is a placeholder for the actual keys in your object. You use dot notation when you're accessing properties on the object and the thing to the right of the dot is the actual name of the property, or in your example, sample.start

Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • Thanks! The following clarifys this: var obj = { name: "stackoverflow", age: 12 } var key = "name"; console.log(obj.key); //undefined – Alan Oct 17 '14 at 15:17