Home  >  Article  >  Web Front-end  >  Introduction to operators == and === in JavaScript_javascript skills

Introduction to operators == and === in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:001264browse

In JavaScript, both the == and === operators can be used to determine whether two values ​​are equal; the difference is that if the two value types are inconsistent, the === operator will directly return false, while The == operator will be judged after type conversion. The detailed judgment rules are as follows:

=== Judgment rules for operators

1. If the types of the two values ​​are inconsistent, return false.
2. If the two values ​​have the same type and the same value, return true. NaN is a special case, NaN===NaN returns false.
3. If the two values ​​​​are both of object type, then just like Java, unless the two references are consistent (reference points to the same object address), even if the content in the object is exactly the same, the two values ​​​​are considered to be inconsistent, and the corresponding operations are performed will return false. For example, if you create two new arrays with exactly the same contents, and perform the === operation on them, the return result is false - although their contents are exactly the same, they still belong to two different objects.
4.0===-0 returns true.

==Judgment rules for operators

The

== operator will convert the type of the value before comparison. The type conversion follows the following principles: it is first converted to a number before comparison, and the Date object is first converted to a string before comparison. The specific judgment rules are as follows:

1. If the two value types are consistent, perform the === operation and return.
2.null==undefined is true.
3. true will be converted into 1 before comparison, false will be converted into 0 before comparison.
4. If one of the values ​​is an object, convert it into a number before comparison, except for Date objects.
5. If one of the values ​​is a Date object, convert it into a string before comparison.

Experiment

Copy code The code is as follows:

console.log("3" === 3);//false
console.log(NaN === NaN);//false
var a = {x:1, y:2};
var b = {x:1, y:2};
var c = a;
console.log(a === b);//false
console.log(a === c);//true
console.log(0 === -0);//true

console.log("3" == 3);//true
console.log(null == undefined);//true
console.log(true == 1);//true
console.log(true == 9);//false

console.log([9] == 9);//true
console.log([9] == "9");//true

var d = new Date();
var s = d.toString();
var n = d.valueOf();
console.log(d == s);//true
console.log(d == n);//false

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn