小于等于运算符:使用NaN [英] The Less-than-or-equal Operator: With NaN

查看:133
本文介绍了小于等于运算符:使用NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用小于或等于运算符时,这可以在抽象关系比较算法的支持下进行. 例如.

When we use The Less-than-or-equal Operator this is work under the hood with The Abstract Relational Comparison Algorithm. For example.

a <= b;

像这样转换为JavaScript

Convert to JavaScript like this

!(b < a)

EcmaScript Spesification说( http://www .ecma-international.org/ecma-262/5.1/#sec-11.8.5 ),这表明至少一个操作数比返回的undefined少NaN 这就是

And EcmaScript Spesification says (http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5) which indicates that at least one operand is NaN less than return undefined And this is meaning

var a = 1;
var b = "asd"
a < b // b.toNumber() => NaN and this is operation return undefined (false)

如果我们这样使用

var a = 1;
var b = "asd"
a <= b // this convert to  !(b < a) and (b<a) return undefined
// and !(undefined) must be true

但是EcmaScript spesification表示这返回false.这对我来说很有趣,这是什么原因?

But EcmaScript spesification says this is return false. This is interesting for me what is reason this?

推荐答案

虽然< =确实使用了抽象关系比较算法,但a <= b并不等同于!(b < a).它等效于b < a !== false ? false : true(其中<代表抽象关系比较算法,而不是JavaScript <运算符,该运算符永远不能求和为undefined),当b < a为真时,其行为与!(b < a)相同或完全false,但是当b < a通常为false时,行为就不会相同.如果b < a计算为undefined,则整个表达式将计算为false.

While <= does use the Abstract Relational Comparison Algorithm, a <= b isn't equivalent to !(b < a). It is equivalent to b < a !== false ? false : true (where < represents the Abstract Relational Comparison Algorithm, not the JavaScript < operator which can never evaluate to undefined), which behaves the same as !(b < a) when b < a is truthy or exactly false, but does not behave the same when b < a is falsey in general. If b < a evaluates to undefined, the whole expression will evaluate to false.

这是在步骤6的规范中定义的,此处: https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.3

This is defined in the spec at step 6 here: https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.3

  1. r 是执行抽象关系比较的结果 rval < lval ,其中 LeftFirst 等于 false .
  2. 如果 r true 未定义,则返回 false .否则,返回 true .
  1. Let r be the result of performing abstract relational comparison rval < lval with LeftFirst equal to false.
  2. If r is true or undefined, return false. Otherwise, return true.

抽象关系比较算法只能计算为truefalseundefined;因此第6步中的否则"仅在rfalse时适用,从而使a <= b等效于b < a !== false ? false : true(同样,其中<代表抽象关系比较算法).

The Abstract Relational Comparison Algorithm can only evaluate to true, false, or undefined; so the "Otherwise" in step 6 can only apply when r is false, making a <= b equivalent to b < a !== false ? false : true (again, where < represents the Abstract Relational Comparison Algorithm).

这篇关于小于等于运算符:使用NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆