JavaScript中的操作符==与===介绍_javascript技巧

WBOY
Release: 2016-05-16 16:23:00
Original
1189 people have browsed it

JavaScript中,==与===操作符均可用于判断两个值是否相等;不同之处在于,如果进行判断的两个值类型不一致,===操作符会直接返回false,而==操作符则会在类型转换后再进行判断。详细的判断规则如下:

===操作符的判断规则

1.如果两个值的类型不一致,返回false。
2.如果两个值的类型一致,值一致,返回true。NaN是一个特例,NaN===NaN返回false。
3.如果两个值均为object类型,那么与Java一样,除非两者引用一致(reference指向同一个对象地址),不然即使object中的内容完全一样,也认为这两个值不一致,相应的操作将返回false。比如,新建两个内容完全一样的数组,对它们进行===操作后返回结果为false — 虽然它们的内容完全一样,但还是属于两个不同的对象。
4.0===-0返回true。

==操作符的判断规则

==操作符会将值进行类型转换后再进行比较,其类型转换遵循以下原则:优先转换成number后进行比较,Date对象则优先转换成string后进行比较。具体判断规则如下:

1.如果两个值类型一致,执行===操作后返回。
2.null==undefined为true。
3.true将转换成1后进行比较,false将转换成0后进行比较。
4.如果其中一个值为对象,则将其转换成number后再进行比较,Date对象除外。
5.如果其中一个值为Date对象,则将其转换成string后再进行比较。

实验

复制代码代码如下:

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!