小于或等于 (<=)
如果左操作数小于或等于右操作数,则小于或等于 (<=) 运算符返回 true,否则返回 false。
¥The less than or equal (<=) operator returns true if the left operand is less than or equal to the right operand, and false otherwise.
Try it
语法
描述
¥Description
使用与 少于 运算符相同的算法来比较操作数,交换操作数并将结果取反。x <= y 一般等价于 !(y < x),除了 x <= y 和 x > y 都是 false 的两种情况:
¥The operands are compared using the same algorithm as the Less than operator, with the operands swapped and the result negated. x <= y is generally equivalent to !(y < x), except for two cases where x <= y and x > y are both false:
- 如果其中一个操作数转换为 BigInt,而另一个操作数转换为无法转换为 BigInt 值的字符串(传递给
BigInt()时会抛出 语法错误)。 - 如果其中一个操作数转换为
NaN。(例如,无法转换为数字的字符串,或undefined。)
此外,x <= y 在 y 之前将 x 强制为原语,而 y < x 在 x 之前将 y 强制为原语。由于强制转换可能会产生副作用,因此操作数的顺序可能很重要。
¥In addition, x <= y coerces x to a primitive before y, while y < x coerces y to a primitive before x. Because coercion may have side effects, the order of the operands may matter.
x <= y 一般等同于 x < y || x == y,除了少数情况:
¥x <= y is generally equivalent to x < y || x == y, except for a few cases:
- 当
x或y其中一个为null,另一个不是null且在 强制为数字 时变为 0 时(包括0、0n、false、""、"0"、new Date(0)等):x <= y是true,而x < y || x == y是false。 - 当
x或y之一为undefined,另一个为null或undefined之一时:x <= y是false,而x == y是true。 - 当
x和y是同一个对象,在 少于 的第一步之后变成NaN时(比如new Date(NaN)):x <= y是false,而x == y是true。 - 当
x和y是不同的对象,在 少于 的第一步之后变成相同的值时:x <= y是true,而x < y || x == y是false。
示例
字符串与字符串的比较
字符串与数字的比较
数字与数字的比较
数字与 BigInt 比较
比较布尔值、null、未定义、NaN
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-relational-operators |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also