This is the 19th day of my participation in The August More Wen Challenge.

What are the results

What, so vexatious problem, a == 1 && A == 2 && A == 3 I directly is the console paste, well, in line with expectations, or I should think my understanding of JS is not what problem 😅.

How to return true

If you’re in an interview and the interviewer is asking you to implement this equation, can we really do it? The answer is of course ok, otherwise the interviewer asks so vexatious question, you should question him to have what deviation to js understanding 😏

But anyway, this is an easy question, we could define the value of a to be equal to both 1 and 2 and 3, right? What? You said it wasn’t okay, so let’s try something different.

A == 1&&a == 2&&a == 3 converts to a == a + 1&&a == a + 2, can we make this equation true? It’s really simple:

const a = Infinity;
console.log(a == a + 1 && a == a + 2); // true
Copy the code

Look, infinity is infinity no matter what you add (akimbo), isn’t it suddenly clear? Of course that’s not the exact answer to this question, so let’s move on.

Implicit type conversion

So what we want to do is actually very simple, to make a == a + 1&&a == a + 2 true when a = 1. Implicit conversions: Js implicit conversions: js implicit conversions: js implicit conversions

When the object type is compared to the original type for equality, the object type is converted to the original type according to the ToPrimitive rule

We can then use this rule to define a as an object and add a valueOf() method to it so that we can perform some events when we compare.

const a = {
    index: 1.valueOf: function() {
        return this.index++; }}Copy the code

So when a is compared to a number, the valueOf event of A is called.

After executing the current judgment, the index variable in A increases, which neatly implements our requirements. Well, it seems that MY understanding of JS is still no problem.

conclusion

This problem is actually a small technique of data type conversion, the current daily development may not be used, but the data type implicit conversion is very important, we come 💪🏻

The front end is long and long. We are all on the road. We hope to communicate with our friends and make progress together. Keep updating ing…..