search
HomeWeb Front-endJS TutorialInterview question: How to make 'a==1&&a==2&&a==3' true?

Interview question: How to make 'a==1&&a==2&&a==3' true?

Mar 13, 2023 pm 08:06 PM
javascriptInterview questions

This article will share with you a classic interview question to see how to make "a==1&&a==2&&a==3" true? Through this interview question, I learned the knowledge points contained in it. I hope it will be helpful to everyone!

Interview question: How to make 'a==1&&a==2&&a==3' true?

1. Problem analysis

if (a == 1 && a == 2 && a == 3) {
  console.log('Win')
}

How to make the code in if execute and successfully print out on the consoleWin ?

When I first saw the question, I was blinded. How could such a contradictory situation happen? It is equivalent to how a person can be a child and an adult at the same time. Or the elderly?

Interview question: How to make 'a==1&&a==2&&a==3' true?

#Calm down and find some clues.

It doesn’t say let a be equal to 1 2 3 at the same time.

And js runs in a single thread. Even if they are written on one line, they are executed from left to right. So they are not from the same period in time and space.

Since they are not from the same period, then of course a person can become a child, then an adult, and then an elderly person.

Interview question: How to make 'a==1&&a==2&&a==3' true?

Back to the question, if I want this condition to be true, I need to obtain a once and let it increase by 1 at the same time.

2. Solution

2.1 toString

The first method is to use [implicit conversion in the judgment process ]toString method. I elaborated in my other articleWhy [] == ![] results in true?.

const a = {
  _a: 0,
  toString: function() {
    return ++a._a
  }
}

Run it once, add 1 to _a, and then return.

Because toString is the default method above Object.prototype, so this method is equivalent to changing the normal The toString method in the implicit conversion is intercepted.

Knowledge points involving prototypes and prototype chains

The problem can be solved.

Some friends in the comment area said that setting a = true can also solve the problem. Very misleading indeed. In fact, it confuses the priority of implicit conversion. Simply put, implicit conversion consists of two parts: Conversion rules and conditions that trigger conversion. ifThe whole package triggers the conversion rule of Boolean(), == and the string triggers toString()## on the right side # conversion rules.

Back to this question, the right side of

== is a number, and the JS running line is from left to right. Therefore, what is triggered at this time is the Number() rule. After converting the true on the left into 1, the types on both sides are the same After that, naturally no more rules will be triggered, and it no longer constitutes an implicit conversion. So 1 == 1 && 1 == 2 && 1 == 3 is not true.

I remember it now, and it will be better than memorizing it during the interview.

Now I will simply modify the question, changing double equals into

three What to do when ?

Everyone knows that

=== determines the type first and then the value. toString here has converted the object into a string by default. If toStirng is used, the result will not be true.

2.2 defineProperties

Data interception method using objects:

Object.defineProperties(window, {
  _a: {
    value: 0,
    writable: true
  },
  a: {
    get: function() {
      return  ++_a
    }
  }
})

Involving object accessor related content

I don’t know if it reminds you of the watch or computed instructions in Vue. ?

3. Summary

Whether you can do this interview question has no meaning. But it is very interesting to understand the knowledge points contained in this interview question.

From implicit type conversion to prototype and prototype chain, and finally to the access rights attribute of the object. If you want to continue to extend, the implementation principle of Vue's two-way binding, the implementation of static in class, etc.

These are why it is necessary to build a front-end knowledge system that can extend from one knowledge point to other related knowledge points.

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of Interview question: How to make 'a==1&&a==2&&a==3' true?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor