I believe that people who are new to JS will be confused by its equality judgment. Take a look at the following code. How many can you answer correctly?
NaN === NaN // false NaN == NaN // false Object.is(NaN, NaN) // true 0 == false // true 1 == true // true Number(null) === 0 // true null == 0 // false
Javascript provides three different value comparison operations, namely strict equality, loose equality, and Object.is. After checking the information today, I made a summary. I hope the following content can be helpful to everyone. Please help. If there are any mistakes, you are welcome to correct me.
[Related course recommendations: JavaScript video tutorial]
1. Strict equality x === y judgment logic
1. If the data type of x is different from the data type of y, return false;
2. If x is Number type
● x is NaN, return false
● y is NaN, return false
● The value of x is equal to the value of y, return true
● x is 0, y is -0, return true
● x is -0, y is 0, return true
● Otherwise return false
3. Other types refer to SameValueNonNumber(x, y)
● Assertion: x, y is not Number type;
● Assertion: x, y have the same data type;
● x is undefined, y is undefined return true;
● x is null, y is null, return true;
● x is a string type, if and only if the character sequences of x and y are exactly the same ( The length is the same and the characters at each position are the same) return true, otherwise return false;
● If x is a Boolean type, return true when x and y are both true or false, otherwise return false ;
● If x is a symbol type, when x and y are the same symbol value, return true, otherwise return false;
● If x, y are the same object value, return true , otherwise return false;
NaN === NaN // false undefined === undefined // true null === null // true undefined === null // false
2. Relaxed equality x == y
1. If x and y have the same type, return the result of x===y ;
2. If x is null, y is undefined, return true;
3. If x is undefined, y is null, return true;
4. If If x is a numerical value and y is a string, return x == ToNumber(y);
5. If x is a string and y is a numerical value, return ToNumber(x) == y;
6. If x is a Boolean type, return the result of ToNumber(x)==y;
7. If y is a Boolean type, return the result of x==ToNumber(y);
8. If x is one of String, Number or Symbol and Type(y) is Object, return the result of x==ToPrimitive(y)
9. If Type(x) is Object and Type (y) is one of String, Number or Symbol, and returns the result of ToPrimitive(x)==y
10. Others return false
12 == '0xc' // true, 0xc是16进制 12 == '12' // true 12 == '12c' // false, 说明ToNumber转换是用的Number()方法
Note:
Number(null) === 0
But
null == 0 // false,
2.1 ToNumber converts a value to a numeric type
1. If it is a boolean type, true returns 1, false returns 0;
2. If it is a numerical value, it is simply passed in and returned;
3. If it is null, it returns 0
4. If it is undefined, it returns NaN;
5. If it is a string, if the string only contains numbers, convert it into a decimal number; if it is a valid floating point format, convert it into the corresponding floating point value; if it is binary or hexadecimal Convert it into the corresponding decimal value;
6. If it is an object, call the object's valueOf() method, and then convert it according to the previous rules. If the valueOf return value is NaN, call the toString() method, and then Convert the returned string according to the previous rules
2.2 ToPrimitive
toPrimitive(A) by trying to call A.toString() and A.valueOf() methods , convert parameter A into a primitive value (Primitive);
The primitive types in JS are: Number, String, Boolean, Null, Undefined;
The return of the valueOf() method of different types of objects Value:
Object | Return value |
---|---|
Array | Return the array object itself. |
Boolean | Boolean value |
Date | The stored time is from January 1, 1970 The number of milliseconds starting at midnight UTC |
Function | The function itself |
Number | Number value |
Object | The object itself. This is the default, you can override the valueOf method of the custom object |
String | String value |
// Array:返回数组对象本身 var array = ["ABC", true, 12, -5]; console.log(array.valueOf() === array); // true // Date:当前时间距1970年1月1日午夜的毫秒数 var date = new Date(2013, 7, 18, 23, 11, 59, 230); console.log(date.valueOf()); // 1376838719230 // Number:返回数字值 var num = 15.26540; console.log(num.valueOf()); // 15.2654 // 布尔:返回布尔值true或false var bool = true; console.log(bool.valueOf() === bool); // true // new一个Boolean对象 var newBool = new Boolean(true); // valueOf()返回的是true,两者的值相等 console.log(newBool.valueOf() == newBool); // true // 但是不全等,两者类型不相等,前者是boolean类型,后者是object类型 console.log(newBool.valueOf() === newBool); // false // Function:返回函数本身 function foo(){} console.log( foo.valueOf() === foo ); // true var foo2 = new Function("x", "y", "return x + y;"); console.log( foo2.valueOf() ); /* ƒ anonymous(x,y ) { return x + y; } */ // Object:返回对象本身 var obj = {name: "张三", age: 18}; console.log( obj.valueOf() === obj ); // true // String:返回字符串值 var str = "http://www.xyz.com"; console.log( str.valueOf() === str ); // true // new一个字符串对象 var str2 = new String("http://www.xyz.com"); // 两者的值相等,但不全等,因为类型不同,前者为string类型,后者为object类型 console.log( str2.valueOf() === str2 ); // false
3.同值相等
同值相等由 Object.is 方法判断:
● 两个值都是 undefined
● 两个值都是 null
● 两个值都是 true 或者都是 false
● 两个值是由相同个数的字符按照相同的顺序组成的字符串
● 两个值指向同一个对象
● 两个值都是数字并且
○ 都是正零 +0,
○ 或者都是负零 -0,
○ 或者都是 NaN
○ 都是除零和 NaN 外的其它同一个数字
Object.is('foo', 'foo'); // true Object.is(window, window); // true Object.is('foo', 'bar'); // false Object.is([], []); // false var foo = { a: 1 }; var bar = { a: 1 }; Object.is(foo, foo); // true Object.is(foo, bar); // false Object.is(null, null); // true Object.is(true, 'true') // false // 特例 Object.is(0, -0); // false Object.is(0, +0); // true Object.is(-0, -0); // true Object.is(NaN, 0/0); // true
4.零值相等
与同值相等类似,不过会认为 +0 与 -0 相等。
小结
=== 不做类型转换,当两边的数类型不相同时,直接返回false;当前类型相同且都是数值类型的时候,有一个是NaN,那么结果就是false, 另外 +0 === -0
==运算符,当两边操作数类不相同时会做隐式转换,然后才进行比较,这样的话就会出现 false == 0, '' == false 等现象, 但是Object.is不会做这种转换
本文来自 js教程 栏目,欢迎学习!
The above is the detailed content of The difference between equality judgment ===, == and Object.is() in js. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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 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.

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

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.

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.

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.


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

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

Hot Article

Hot Tools

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Atom editor mac version download
The most popular open source editor

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