You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
注意图片中的第7条:If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
第9条:If Type(x) is Object and Type(y) is either String or Number,return the result of the comparison ToPrimitive(x) == y.
// ECMA-262, section 9.1, page 30. Use null/undefined for no hint,// (1) for number hint, and (2) for string hint.functionToPrimitive(x,hint){// Fast case check.if(IS_STRING(x))returnx;// Normal behavior.if(!IS_SPEC_OBJECT(x))returnx;if(IS_SYMBOL_WRAPPER(x))throwMakeTypeError(kSymbolToPrimitive);if(hint==NO_HINT)hint=(IS_DATE(x)) ? STRING_HINT : NUMBER_HINT;return(hint==NUMBER_HINT) ? DefaultNumber(x) : DefaultString(x);}// ECMA-262, section 8.6.2.6, page 28.functionDefaultNumber(x){if(!IS_SYMBOL_WRAPPER(x)){varvalueOf=x.valueOf;if(IS_SPEC_FUNCTION(valueOf)){varv=%_CallFunction(x,valueOf);if(IsPrimitive(v))returnv;}vartoString=x.toString;if(IS_SPEC_FUNCTION(toString)){vars=%_CallFunction(x,toString);if(IsPrimitive(s))returns;}}throwMakeTypeError(kCannotConvertToPrimitive);}// ECMA-262, section 8.6.2.6, page 28.functionDefaultString(x){if(!IS_SYMBOL_WRAPPER(x)){vartoString=x.toString;if(IS_SPEC_FUNCTION(toString)){vars=%_CallFunction(x,toString);if(IsPrimitive(s))returns;}varvalueOf=x.valueOf;if(IS_SPEC_FUNCTION(valueOf)){varv=%_CallFunction(x,valueOf);if(IsPrimitive(v))returnv;}}throwMakeTypeError(kCannotConvertToPrimitive);}
先看看官方对于隐式转换的定义
注意图片中的第7条:If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
第9条:If Type(x) is Object and Type(y) is either String or Number,return the result of the comparison ToPrimitive(x) == y.
那么我们以[] == false为例,先对x进行ToPrimitive(x),在对y进行ToNumber(y).
这里我们先来了解一下ToPrimitive()和ToNumber()的源码
ToPrimitive和ToNumber
ToPrimitive
大致的代码逻辑是:
ToNumber
ToString
那么[].valueOf()的结果是[],在对[]调用toString的方法,得到的结果是""。
而true调用ToNumber的方法得到的结果是1。
"" == 1 返回的是false,所以[] == true,返回false。
那么我们再来看看!![] == true是怎么解读的?
根据优先级,先进行!操作。
所以!![]相当于!!(ToBoolean([]))
ToBoolean源码
从源码中,我们得知,null,undefined,0,"",false,NaN,返回false。其余都是返回true。
那么!![],转换之后等于!!true,即true。
那其余的一个就留给大家自己分析啦!!!
The text was updated successfully, but these errors were encountered: