Looking at this piece of code:
for (var i = 0, f; f = families[i]; i++) {
}
I haven't actually seen a loop like this before and I want to be sure I understand it correctly.
Am I correct in assuming that iffamilies.length == 2
that the 2nd part of t开发者_JAVA技巧he for
line would return false on f = families[2]
?
I would have thought it would need to be something like f == families[2]
in order to return false.
f = families[i]
is an expression that returns the value of families[i]
. (It also has the side-effect of assigning that value to f
)
If families.length === 2
then families[2] === undefined
thus the expression returns undefined
which is falsey and breaks the loop.
For more hacking fun you can turn
for (var i = 0, f; f = families[i]; i++) {
// body
}
into
for (var i = 0, f; f = families[i++]; /* body */);
You may have to string replace ;
with ,
and string replace i
with i-1
. You also just murdered readability.
It should also be pointed out that the for loop is silly for readability.
Object.keys(families).forEach(function(key) {
var family = families[key];
/* body */
});
Is significantly more readable.
This looks like kind of a silly way of doing
for(var i in families) {
if (families.hasOwnProperty(i)) {
// do whatever you want with families[i]
console.log(families[i]);
}
}
精彩评论