JavaScript中的强制
作者:互联网
我想知道一些关于胁迫的事情.
当你这样做时:
1 == true // true
哪一个被强制进入哪一个?是左边还是右边的?
当你这样做
undefined == null // true
它是如何工作的?
它以哪种顺序尝试转换它?
通过实例:
1) String(undefined) == String(null) // false
2) Number(undefined) == Number(null) // false
3) Boolean(undefined) == Boolean(null) // true
它是否首先尝试强制左侧操作数?那么对吧?那么两个?
编辑:
正如评论中所解释的:
“不是重复.虽然两个问题都是关于类型强制的,但是这个问题要求哪个操作数被强制转换为另一个.另一个是关于评估强制类型时的真实来源”
解决方法:
该过程在7.2.12 Abstract Equality Comparison中描述:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.
Return false.
因此,不是强迫一方,而是另一方,或类似的东西,更多的是解释器通过上面的列表直到找到匹配条件,并执行结果命令,这可能只涉及强制左侧,或仅右边(并且,很少,两者,如果达到递归命令,例如使用true ==’1′,这将满足条件8,变为1 ==’1′,满足条件6并变为1 == 1,满足条件3并解析为真)
标签:coercion,javascript 来源: https://codeday.me/bug/20190928/1828804.html