網頁

[Javascript] == vs ===

== 和 === 依據變數的型別會有不同的比較方式:
非Object型別(String , Int...):
==  會比較 'value'
=== 會比較 'value' & 'type'
Example:
 
        var x = 5;
        var y = '5';

        if (x == y) {
            console.log('same');
        } else {
            console.log('not same');
        }
result:same
 
        var x = 5;
        var y = '5';

        if (x === y) {
            console.log('same');
        } else {
            console.log('not same');
        }
result:not same

Object型別:
==  和 === 一樣都比較 "Reference"
        var obj1 = {
            name: "Asin",
            weather: "Sunny"
        }

        var obj2 = {
            name: "Asin",
            weather: "Sunny"
        }

        var obj3 = obj2;

        var test1 = obj1 == obj2;
        var test2 = obj2 == obj3;
        var test3 = obj1 === obj2;
        var test4 = obj2 === obj3;

        console.log("test1 : " + test1);
        console.log("test2 : " + test2);
        console.log("test3 : " + test3);
        console.log("test4 : " + test4);
Result:
test1 : false
test2 : true
test3 : false
test4 : true

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...