javascript 无语的==

今天面试不小心掉进坑了,大公司特别喜欢考javascript,而且专门挑很tricky的case。

javascipt的==简直就是黑魔法,以前偷懒总是用,感觉也没有问题,可是准备面试就需要有寻根问底的精神。

原题问[]==false; ![]==false console输出什么。结果是都是true 

Since the left and right sides of the equality are two different types, JavaScript can't compare them directly. Hence, under the hood, JavaScript will convert them to compare. First, the right side of the equality will be cooereced to a number and number of true would be 1.

After that, JavaScript implementation will try to convert [] by usingtoPrimitive (of JavaScript implementation). Since [].valueOf is not primitive, it will use toString and will get ""

Now you are comparing "" == 1 and still, the left and right are not the same type. Hence, the left side will be converted again to a number and empty string will be 0.

Finally, they are of same type. You are comparing 0 === 1 which will be false.

一般做逻辑判断应该是转换为bool类型,javascript最终却是转换为数字来比较。

 

1.一个数字与一个字符串,字符串转换成数字之后,进行比较。
2. true转换为1,false转换为0进行比较。// 1==true返回true;2==true返回false;
3. 数组会被转换为原始类型之后进行比较(先valueof,不行的话再toString)。var a = [1,2], a==true这里的a会被转换为"1,2"又因为true被转成了数字,所以这里的a最终被转成Number(a),也就是NaN。
结合上面3点得出a==true最终变成 NaN==1 ,所以返回false。[1]==true;//true;[2]==true;//false!!

 

参见ecma262:http://www.ecma-international.org/ecma-262/6.0/index.html#sec-abstract-equality-comparison

7.2.12Abstract Equality Comparison

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

    1. ReturnIfAbrupt(x).
    2. ReturnIfAbrupt(y).
    3. If Type(x) is the same as Type(y), then
      1. Return the result of performing Strict Equality Comparison x === y.
    4. If x is null and y is undefined, return true.
    5. If x is undefined and y is null, return true.
    6. If Type(x) is Number and Type(y) is String,
      return the result of the comparison x == ToNumber(y).
    7. If Type(x) is String and Type(y) is Number,
      return the result of the comparison ToNumber(x) == y.
    8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
    9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
    10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
      return the result of the comparison x == ToPrimitive(y).
    11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
      return the result of the comparison ToPrimitive(x) == y.
    12. Return false.

 

你可能感兴趣的:(javascript 无语的==)