Javascript object property not available

I seem to have a problem with the property area of ​​the objects. I would like to bring each of the objects Messageobjects titleand Messagean element select, but it does not work ! What am I doing wrong

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    function Message(title, message) {
        this.title=title;
        this.message=message;
        this.getTitle = function(){
            return this.title;
        };
        this.getMessage = function(){
            return this.message;
        };
    }
    var messages = new Array(
        new Message("First Title", "This is the first message"),
        new Message("Second Title", "This is another message")
    );
    function updateSelect () {
        $("#cannedMessages_button").empty();
        for (c in messages) {
            // First try, with getters and setters
            $("#cannedMessages_button").append($('<option>', { value : c.getMessage() , text : c.getTitle() }));
            // Second try, directly
            $("#cannedMessages_button").append($('<option>', { value : c.message , text : c.title }));
        }
    }
    updateSelect();
});
</script>
</head><body>
<form><select id="cannedMessages_button"></select></form>
</body></html>

I can verify that foreach actually does two iterations, but I cannot get the values ​​from the objects.

0
source share
2 answers

do not use for (c in messages).

in Intended for iterating over the properties of an object, not for iterating over values ​​in an array.

Use tried and true

for(var i = 0; i < messages.length; i++) {
...
}

In addition, you do not put their own methods getTitleand getMessageon the prototype, which is wasteful.

+1

for in js:

for(var key in obj)
    {
        var currentElement = obj[key];
    }
0

All Articles