About the == and === comparison operations
- The js == operator involves different types of comparisons and often uses a lot of defined implicit conversion rules, most of which are too convoluted (or unnecessary) for most front-end developers to fully grasp. So most development teams disable == and! The = operator takes the === and! == operator substitution.
Primitive type and object comparison
If the value of the original type is compared with the object, the object is first converted to the value of the original type and then compared with the value of the original type. ValueOf is first called when an object is converted to a valueOf the original type, and toString is then called if the return is still an object.
- Columns such as
Const a = {toString() {console.log(' call toString') // prints 2 call toString return 0}, ValueOf () {console.log(' call valueOf') // prints 1 Call valueOf return {}}} console.log(a == 0) // Returns trueCopy the code
- So this gives us
Plan a
Const a = {num: 1, valueOf() {return a.num++}} console.log(a == 1 && a == 2 && a == 3) // Returns trueCopy the code
Scheme 2
const a = { num: 1, toString(){return a.num++}, valueOf() {return {}}} console.log(a == 1 && a == 2 && a == 3) // Returns trueCopy the code
Plan 3
Array type is also an object, and array calls toString with its own join(‘,’) method passing in the argument ‘,’, so we can have a neat method.
Const a = [1,2,3] a.in = a.hift console.log(a == 1&& a == 2&& a == 3) // Returns trueCopy the code
Option 4: Use Object.defineProperty
let num = 0; Object.defineproperty (window, 'a', {// Note that the non-browser environment global may not be window get() {return ++num; }}); Console. log(a == 1&&a == 2&&a == 3) // Returns trueCopy the code
Scheme 5: Use Symbol. ToPrimitive
Symbol. ToPrimitive: Symbol. ToPrimitive is a built-in Symbol value that exists as a function value attribute of an object and is called when an object is converted to its original value.
ES6 new primitive type Symbol, through the Symbol method toPrimitive can have a scheme.
Const a = {[Symbol toPrimitive] : ((num) = > () = > num++)} (1) the console, log (a = = 1 & & & & a = = a = = 2 3) / / return trueCopy the code