Web Front-end
JS Tutorial
Introduction to implicit type conversion of comparison operators in JavaScript (with examples)Introduction to implicit type conversion of comparison operators in JavaScript (with examples)
This article brings you an introduction to implicit type conversion of comparison operators in JavaScript (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
I believe you often see '==' and '===' in your code, but do you really understand comparison operators and the implicit conversions therein? Let's re-understand comparison operators today .
Congruence operator===
Description: Strict matching, no type conversion, the data type and value must be exactly the same
先判断类型,如果类型不是同一类型的话直接为false; 1 对于基本数据类型(值类型): Number,String,Boolean,Null和Undefined:两边的值要一致,才相等 console.log(null === null) // true console.log(undefined === undefined) // true 注意: NaN: 不会等于任何数,包括它自己 console.log(NaN === NaN) // false 2 对于复杂数据类型(引用类型): Object,Array,Function等:两边的引用地址如果一致的话,是相等的 arr1 = [1,2,3]; arr2 = arr1; console.log(arr1 === arr2) // true
Equality operator==
Non-strict matching: Type conversion is possible, but there are five situations with preconditions
(The following code uses x == y as an example)
x and y are both null or undefined:
Rules: No implicit type conversion, return true unconditionally
console.log ( null == undefined );//true console.log ( null == null );//true console.log ( undefined == undefined );//true
x or y is NaN: NaN is not equal to any number
Rules: No implicit type conversion, return unconditionally false
console.log ( NaN == NaN );//false
x and y are string, boolean, number
Rules: There is implicit type conversion, which will convert data that is not number type into number
console.log ( 1 == true );//true (1) 1 == Number(true)
console.log ( 1 == "true" );//false (1) 1 == Number('true')
console.log ( 1 == ! "true" );//false (1) 1 == !Boolean('true') (2) 1 == !true (3) 1 == false (4)1 == Number(false)
console.log ( 0 == ! "true" );//true
console.log(true == 'true') // false
x or y is Complex data type: The original value of the complex data type will be obtained first and then left compared
The original value of the complex data type: First call the valueOf method, and then call the toString method
valueOf: generally returns itself by default
Array toString: By default, the join method will be called to splice each element and the spliced string will be returned.
console.log ( [].toString () );//空字符串
console.log ( {}.toString () );//[object Object]
注意: 空数组的toString()方法会得到空字符串,
而空对象的toString()方法会得到字符串[object Object] (注意第一个小写o,第二个大写O哟)
console.log ( [ 1, 2, 3 ].valueOf().toString());//‘1,2,3’
console.log ( [ 1, 2, 3 ] == "1,2,3" );//true (1)[1,2,3].toString() == '1,2,3' (2)'1,2,3' == '1,2,3'
console.log({} == '[object Object]');//true
x and y are both complex data types:
The rule only compares addresses, and returns true if the addresses are consistent, otherwise Return false
var arr1 = [10,20,30];
var arr2 = [10,20,30];
var arr3 = arr1;//将arr1的地址拷贝给arr3
console.log ( arr1 == arr2 );//虽然arr1与arr2中的数据是一样,但是它们两个不同的地址
console.log ( arr3 == arr1 );//true 两者地址是一样
console.log ( [] == [] );//false
console.log ( {} == {} );//false
Classic Interview Questions
注意:八种情况转boolean得到false: 0 -0 NaN undefined null '' false document.all()
console.log([] == 0); //true
// 分析:(1) [].valueOf().toString() == 0 (2) Number('') == 0 (3) false == 0 (4) 0 == 0
console.log(![] == 0); //true
// 分析: 逻辑非优先级高于关系运算符 ![] = false (空数组转布尔值得到true)
console.log([] == []); //false
// [] 与右边逻辑非表达式结果比较
//(1) [] == !Boolean([]) (2) [] == !true (3)[] == false (4) [].toString() == false (5)'' == false (6)Number('0') == Number(false)
console.log([] == ![]); //true
onsole.log({} == {}); //false
// {} 与右边逻辑非表达式结果比较
//(1){} == !{} (2){} == !true (3){} == false (4){}.toString() == false (5)'[object Object]' == false (6)Number('[object Object]') == false
console.log({} == !{}); //false
Abnormal Interview Questions
var a = ???
if(a == 1 && a == 2 && a == 3 ){
console.log(1)
}
//如何完善a,使其正确打印1
//答案
var a = {
i : 0, //声明一个属性i
valueOf:function ( ) {
return ++a.i; //每调用一次,让对象a的i属性自增一次并且返回
}
}
if (a == 1 && a == 2 && a == 3){ //每一次运算时都会调用一次a的valueOf()方法
console.log ( "1" );
}
This article has ended here. For more other exciting content, you can pay attention to the PHP Chinese website The JavaScript video tutorial column!
The above is the detailed content of Introduction to implicit type conversion of comparison operators in JavaScript (with examples). For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft





