Triple equal signs return false for arrays in javascript. why?

后端 未结 4 1769
南方客
南方客 2020-11-27 19:15

I know that === is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. Then why bel

4条回答
  •  孤街浪徒
    2020-11-27 19:38

    because if it's not a primitive type (String, Number, Boolean), if it's an array or an object then the comparison operators will check if it's exactly the same instance. So

    var a = ['as','ds'];
    var b = a;
    var c = ['as','ds'];
    b == a; //will return true; (doesn't matter if it's == or === for non primitive types)
    b == c; //will return false;
    

    so basically you need to define your own method to compare arrays and see if all elements are the same. This sort of function usually doesn't exist because it can be very expensive and there's usually another way to write that sort of thing.

提交回复
热议问题