This chapter introduces the usage of JavaScript equal sign operator. Friends in need can refer to it.
The most basic use of the equal sign operator is to compare whether two operands are equal. See the following code example:
If the two operands are equal, the return value is true, otherwise it returns false.
The above is the most basic usage. Let’s introduce some of its relatively special situations.
The return value of the above code is true.
Many friends may have questions. One is a string and the other is a numeric type. How can the return value be true? Of course, this is definitely wrong in c# or java, but in js, this is not a problem and it will be done. Implicit data type conversion, string will try to be converted to number.
Let’s look at a code example:
The above code will also return true, because true will also be converted implicitly, it will be converted to 1, and false will be converted to false.
Let’s look at another code example:
An object can be directly compared with a number, and the return value is true.
This is because the object will first call the valueOf() method, and if there is no such method, it will try to call the toString() method.
The difference between two equal signs and three equal signs in JavaScript:
We often see the use of three equal signs and two equal signs in JavaScript code. Let’s introduce the difference between them.
Code example:
Example 1:
Example 2:
Your code above demonstrates the two operators. Let’s introduce the difference between them.
Three equal signs congruent operator:
Since it is a congruence operator, the two operands must be exactly the same to be equal. The specific comparison rules are as follows:
1. If two operations are value types, then the two operands must be completely equal to be equal.
2. If it is a reference type, the two operands must point to the same object to be equal.
Two equal sign operators:
This operator is more philanthropic. If the types of the two operands are different during comparison, type conversion will be performed. The specific rules are as follows:
1. If they are value types with the same data type, then the comparison rules are the same as the equality operator.
2. If the two operand types are the same, then they may also be the same:
a: If one is null and one is undefined, then the two are the same.
b: If one is a string and the other is a numerical value, convert the string into a numerical value and then compare.
c: If any value is true, convert it to 1 and compare. If any value is false, convert it to 0 and compare.
d: If one is an object and the other is a numeric value or string, convert the object into a value of the basic type and then compare. The object is converted to the base type using its toString or valueOf method.
The above is the entire content of this article, I hope you all like it.