Firefox Javascript "can't convert to a primitive type"错误是什么意思?



这是我的JavaScript测试代码:

console.log( [] == 'a' );

在我的火狐中运行时,它会给出此错误: "类型错误:无法将 [] 转换为基元类型">

这是什么意思?它似乎不适用于每个浏览器/浏览器版本,或者就我而言,甚至不适用于选项卡。

我打开了两个 chrome 选项卡,如果我在一个选项卡中尝试代码,它会出错,但在另一个选项卡中它工作正常 - 让我对不一致感到非常困惑。

这是显示错误的图片

那么我在这里错过了什么,为什么铬上不一致?任何帮助表示赞赏!

(编辑1( 我发现在 Array 对象上添加/更改一堆原型时会出现错误,那么如何在不导致此错误的情况下添加原型呢?

{
// if I omit the first line, the error does not occur
Array.prototype.join = Array.prototype.concat;
console.log( [] == 'a' );
}

如您所注意的,这是修改Array原型的结果。特别是因为方法toString是在数组和基元值之间的相等性检查期间使用的。

通常,当你使用一个操作数是对象的==时,javascript 将尝试使用 ECMAScript 规范中概述的步骤将对象转换为原语。 第 3 部分和第 4 部分,具体如下:

  1. 如果提示是"字符串",则让methodNames为«"toString","valueOf"。
  2. 否则,让 methodNames 为 «"valueOf"、"toString"»。

如您所见,toString方法将作为尝试将数组转换为原语的一部分被调用。默认情况下,数组valueOf方法不返回基元,并且由于您已经覆盖了toString方法,现在它也不会返回基元!因此,我们跳过步骤5并继续执行步骤6,其中说:

  1. 抛出一个类型错误异常。

下面是一个演示:

const oldToString = Array.prototype.toString;
Array.prototype.toString = function() {
console.log("Array toString method called!");
return "[" + this.join(", ") + "]";
}
// No type error, because we converted to a primitive (in this
// case, a string) successfully.
console.log([1, 2, 3] == "[1, 2, 3]")
Array.prototype.toString = function() {
return {};
}
// Type error, because we tried to convert to a primitive using
// toString, but we got an object back?!
console.log([1, 2, 3] == "[1, 2, 3]")

需要明确的是,这个问题与浏览器差异或 Firefox无关,而是您的修改与所有浏览器都遵循的 ECMAScript 规范相结合的结果。

相关内容

最新更新