1

I want to display all the properties of the object Wine1 along with their respective values .But this code is not working:

<html>
    <head>

    </head>
    <body>
        <input type="button" value="Button" onClick="f1()">
        <script type="text/javascript">
            function f1()
            {
                var Wine1=new Object();
                Wine1.color="Red";
                Wine1.price="50000 USD";
                Wine1.vine-yard="South";
                var record="Wine1<br><br>";

                for(var prop in Wine1)
                {
                    record+=prop+"="+Wine1[prop]+"<BR>";
                }
                record+="<br>";
                document.write(record);
            }
        </script>
    </body>
</html>

Someone please help me to find the mistake.

5
  • 1
    replace Wine1.vine-yard with Wine1['vine-yard'] and it should work fine. Commented Dec 22, 2012 at 14:52
  • @jbabey Wine1.vineYard would be a better replacement. Commented Dec 22, 2012 at 14:53
  • 1
    technically "vineyard" is one word, if it were me it would just be Wine1.vineyard :P but this change and your change could have impact on other places in his code. Commented Dec 22, 2012 at 14:54
  • @jbabey Thanks.You solved my problem. Stackoverflow is an awesome site. Commented Dec 22, 2012 at 14:57
  • record="test"; overwrites the string you carefully built! Did you mean `record += "test"? Commented Dec 22, 2012 at 15:24

1 Answer 1

8
Wine1.vine-yard

vine-yard is an invalid identifier. It probably throws a syntax error. Basically, only _, $ and alphanumeric characters are accepted in identifiers. An identifier is a property name or a variable name.

Also, your loop might show other properties than the ones you defined. Long story short, here is what you need to do:

for (var prop in Wine1) {
    if (Wine1.hasOwnProperty(prop)) {
        record += prop + "=" + Wine1[prop] + "<BR>";
    }
}

Finally, use correct indentation and spaces. It really helps a lot to read your code and see what's wrong.

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

1 Comment

Concerning "other properties", "people know better than to extend Object", but it's still a good idea to do the check.