Sunday, 15 September 2013

javascript - Why are these two pieces of code returning different values? -


I am learning JavaScript through an online book "Supernatural Javascript" - the way a wonderful resource is. I have come to the Data Structure Chapter in this function:

  for the function table (Event, journal) {var table = [0,0,0,0] ;; (Var i = 0; i & lt; journal; height; i ++) {var entry = journal [i], index = 0; If (Heivent (Event, Entry)) Index = = 1; If (entry.squirrel) index + = 2; Table [index] + = 1; } Return table; }  

As you can see that it runs again in an array, and outputs to another orange, depending on the fact that the logic in the first object is: Events I write it a bit differently ...

  for the function table (event, magazine) {var table = [0,0,0,0]; (Var i = 0; i & lt; journal; height; i ++) {var entry = journal [i], index = 0; If (the event (event, entry)) {index + = 1; } If (entry.squirrel) {index + = 2; Table [index] + = 1; }} Return table; }  

The only change, if there is a bracket around the statement, which I thought was the best practice. However, it produces a different value from the first part of the code. Why is this happening? Is there a scope problem that I can not understand ?? If you do not know what I am talking about, then this book has a link to chapter: and a link journal for the object:

Thanks for any help!

In the original code, this:

  if (entry.squirrel Index) = 2; Table [index] + = 1;  

There are actually two unrelated statements:

  if (entry.squirrel) {index + = 2; } Table [index] + = 1;  

This is simply indenting. In Javascript, in most C-derived languages, the same statement after a occurs when the block can be executed when the condition is correct, to include more than one statement, the braces must be used.


No comments:

Post a Comment