Underscore.js used to manipulate the array data is very convenient, today in reading Underscore.js source code found a judgment statement, temporarily did not understand what meaning, then carefully analyzed, and also to the Internet to check the relevant information.
| The code is as follows |
Copy Code |
if (obj.length = = +obj.length) { for (var i = 0,length = Obj.length i < length; i++) { if (Iterator.call (context, obj[i], I, obj) = = = Breaker) Return } } |
Source code such as, please note if judgment, look very strange difficult to understand, first of all, the meaning of this sentence together, if you change the way you will understand, in fact, this sentence is equivalent to another way of writing:
| The code is as follows |
Copy Code |
if (typeof obj.length = = "Number" &&!isnan (obj.length))
|
It seems to be more visible and effective, but why do the authors write this, and then we need to focus on two places:
The first one is ' = = = ', congruent symbol
The second one is the ' + ' plus
Let's talk about the full equals sign, in the general if judgment, we use ' = = ' more, such as if (2 = ' 2 '), when we get the return result is true, but in ' = = ', in this mode, we get the result is false. This is because the strict equality symbol does not convert the object of the comparison to a type.
And again, ' + ', here's the effect, you can do an experiment, in the console to execute the following sentence + ' 2 ', you can see the return value of the number type of 2, in fact, it is not difficult to understand, the ' + ' is actually the number of operations followed by the transformation of the number type.
We are thinking about the author's purpose, if obj is a string type, such as "ABC", we can get the length property, if it's a function, or an array, we can get their length property, However, if it is an object type of data, it may not contain the length attribute. For non-array, non-string, non-function type data, we can try to traverse the data using a for in loop. So it seems that the author of such a writing, but also want to be able to distinguish between the array type of data or class array data such as strings.