Jump to content

Unexpected Result From Comma Operator.


kilp-web@sbcglobal.net

Recommended Posts

I derived the following from an example in "java script: The Definitive Guide".

var j = {x:1, y:2, z:3};for(var prop in j) {    document.write("name: " + prop +  "; value: " + j[prop], "<br>");}

When I noticed the comma after j[prop] in the "document.write()" call, I assumed that it must be a mistake and that a "+" was intended.It turns out that the code works with either a "," or a "+". Given that I changed it to read:

document.write("name: " + prop +  "; value: " + (j[prop], "<br>");

This time, as I expected, the "," returned the "<br>" and not the j[prop]. What was it doing in the case original case before I added the extra parenthesis?Thanks,Jerry

Link to comment
Share on other sites

Document.write takes an unlimited number of parameters. You can separate the parameters with a comma and it will print each one. This line:document.write("name: " + prop + "; value: " + j[prop], "<br>");Tells it to print 2 things, the string that you build and then a "<br>" string.

Link to comment
Share on other sites

I derived the following from an example in "java script: The Definitive Guide".
var j = {x:1, y:2, z:3};for(var prop in j) {    document.write("name: " + prop +  "; value: " + j[prop], "<br>");}

When I noticed the comma after j[prop] in the "document.write()" call, I assumed that it must be a mistake and that a "+" was intended.It turns out that the code works with either a "," or a "+". Given that I changed it to read:

document.write("name: " + prop +  "; value: " + (j[prop], "<br>");

This time, as I expected, the "," returned the "<br>" and not the j[prop]. What was it doing in the case original case before I added the extra parenthesis?Thanks,Jerry

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...