I'm learning Javascript through the online book "Eloquent JavaScript" - Which is an awesome resource by the way. I came across this function in the Data Structures chapter:
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
return table;
}
As you can see it iterates across an array, and outputs another array depending on how many times the first object had the argument:event. I rewrote this slightly different like this...
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)){
index += 1;
}
if (entry.squirrel){
index += 2;
table[index] += 1;
}
}
return table;
}
The only change is the brackets around the if statements, which I thought was best practice. However, it outputs a different value from the first piece of code. Why is this happening? Is there some scope problem that I don't understand?? If you don't know what I'm talking about, here is a link to the chapter in the book: Eloquent JavaScript and a link to the object JOURNAL:JavaScript Object
Thanks for any help!
Aucun commentaire:
Enregistrer un commentaire