Since the end of the study, Lu continued to meet a lot of short and surprising JS code, the inherent special open a diary to record these magical code ideas, the purpose is to learn, watch-based.
1.JavaScript (a ==1 && a== 2 && a==3) possible true?
A question from the stack overflow: links
Foreign interview questions, nothing is impossible.
Solution 1:
Customize the toString (or valueOf) method, each time the call changes the return value, thus satisfying the judging condition.
const a = { i: 1, toString: function () { return a.i++; }}if(a == 1 && a == 2 && a == 3) { console.log('Hello World!');}
ToString () belongs to the object, and when you use = =, if the type of the two parameter is different, then JS attempts to convert one of the types to the same as the other. In the case of the left object here, the number on the right, the first attempt is to call valueOf (if it can be called) to convert the object to a number, and if it fails, then call toString.
The second method, a bit like a decoy, =-=:
var a? = 1;var a = 2;var ?a = 3;if(a?==1 && a== 2 &&?a==3) { console.log("Why hello there!")}
Note the weird spacing in the IF statement (which I copied from your question). This is the half-width hangul (that is, those unfamiliar with Korean), which is a Unicode space character that is not interpreted by the ECMA script as a space character-this means that it is a valid character for an identifier. So there are three completely different variables, one in the hangul after the other, one in the previous and the last one. To make it easier to read, replace the space with _, the same code looks like this:
var a_ = 1;var a = 2;var _a = 3;if(a_==1 && a== 2 &&_a==3) { console.log("Why hello there!")}
hahaha, I generally also by switching the half-angle full-width symbol to facilitate the passage of markdown in the space processing.
There is also a solution is the JS with the statement, the scope of the object is clear (I heard with the statement slow)
var i = 0;with({ get a() { return ++i; }}) { if (a == 1 && a == 2 && a == 3) console.log("wohoo");}
There are many ways to solve this, interested in yourself can explore.
Those dapper & wonderful & surprising JavaScript code----update