如果相等(严格或不严格)运算符对于 undefined
返回 true
...
console.log(undefined == undefined)
...为什么大于或等于运算符返回 false?
console.log(undefined >= undefined)
MDN page表示使用 Abstract Relational Comparison 比较操作数,但指的是大于(或小于)部分。因此,在我看来,大于或等于应该提供相同的相等算法,这不是正确的吗?
最佳答案
Thus, it seems to me that the greater than or equal should provide the same algorithm for equality, isn't that correct?
不,这里不涉及该算法。规范defines the evaluation of >=
作为
- Let lref be the result of evaluating RelationalExpression.
- Let lval be ? GetValue(lref).
- Let rref be the result of evaluating ShiftExpression.
- Let rval be ? GetValue(rref).
- Let r be ? IsLessThan(lval, rval,
true
).- If r is
true
orundefined
, returnfalse
. Otherwise, returntrue
.
所以唯一涉及的算法是 IsLessThan
,如果其操作数还不是数字(或字符串),则会将其转换为数字。
未定义
获取 converted to NaN
和 Number::lessThan
如果任何操作数为 NaN
,则返回 undefined
,根据上面的步骤 6,结果为 false
。
关于javascript - 'greater than or equal' 和 'equality' 运算符关于 'undefined' 的行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71843914/