整数和对象比较的结果是什么?

What is the result of a comparison between an integer and an object?

将对象与整数进行比较时,JavaScript 的行为是什么? 例如:

var result = { test: 'blah' };
if (result < 0) {
    // when is this portion processed?
}

我目前正在使用一个 result 变量,它可以是整数(错误代码)或包含更多详细信息的对象。

我想我可以使用 parseInt()parseFloat(),但我很想知道处理这些情况的最短方法...

您可以先检查结果是否为 result.isInteger() 的整数,如果是则执行任何需要的操作,否则将其视为对象。

我建议您测试 result 变量的类型以确定它是数字还是对象。

测试对象:

typeof result === 'object'

测试一个数字:

Number.isInteger(result)

如果您将对象与整数进行比较,

Javascript 将自动调用对象的 valueOf() 方法。类似地,当与字符串进行比较时,使用 toString() 方法。

如果您不是对象的创建者,可能有也可能没有 valueOf 函数,因此如果您没有创建对象或没有完成一些额外的测试逻辑,使用比较运算符的行为可能会出乎意料并且只是比较对象和整数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

以下代码片段显示了一些实际比较。

var five = { 
  value: 5, 
  valueOf: function() { 
    return this.value 
  } 
};

var billion = { 
  value: 1000000000
};

console.log ( five.valueOf() );
console.log ( billion.valueOf() );
console.log ( billion > five );
console.log ( NaN > five );
console.log ( 6 > five );
console.log ( 4 > five );

var result = {test: 'blah'};

if(result) {
   if (typeof result === 'object') {
     // do something
   } else if (typeof result === 'number') {
     // do something
   }
}

I'm wondering [...] if a general rule has been defined

是的。 JavaScript specification 中描述了这些规则。对于您的示例:

{ test: "blah" } < 0

我已经突出显示了涉及的部分和规则:

11.8.5 The Abstract Relational Comparison Algorithm
[...]
1.a Let px be the result of calling ToPrimitive(x, hint Number).

表达式 { test: "blah" } 最终为 "[object Object]"

3.a Let nx be the result of calling ToNumber(px).

表达式 "[object Object]" 最终为 NaN

3.c If nx is NaN, return undefined.

算法结果为undefined

11.8.1 The Less-than Operator ( < )
[...]
6. If r is undefined, return false. Otherwise, return r.

最后的结果是false.

developer.mozilla.org上的文档说,当操作数A是一个对象,操作数B是一个数字时,JS比较逻辑是这样定义的:

ToPrimitive(A) == B

其中

ToPrimitive(A) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of A.toString and A.valueOf methods on A.

此外,Mozilla JavaScript Reference 指出:

If the method is not overridden in a custom object, toString() returns "[object type]".

Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata.

因此可以说,在与数字进行比较的情况下,对象总是会转换为字符串。

然后这样处理:

ToNumber(A) === B

ToNumber(A) attempts to convert its argument to a number before comparison. Its behavior is equivalent to +A (the unary + operator).

最后,Unary Plus doc 指出:

If it cannot parse a particular value, it will evaluate to NaN.

developer.mozilla.org 上的同一文档提供了一个摘要 table 表明将数字与 NaN 进行比较总是 return 错误。

因此,除非在 提出的场景中,给定的代码应该有效。

但是,为了避免数据结构的错误,@给出的答案 首选约翰·肯尼迪.