今天面试不小心掉进坑了,大公司特别喜欢考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!!