gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:04:34 27 4
gpt4 key购买 nike

这是我的javascript测试代码:

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

在我的 firefox 中运行时出现了这个错误:“类型错误:无法将 [] 转换为原始类型”

这是什么意思?它似乎并不适用于每个浏览器/浏览器版本,或者在我的情况下,甚至是一个选项卡。

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

这是一个 image显示错误

那么我在这里遗漏了什么,为什么 chrome 上的不一致?任何帮助表示赞赏!

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

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

最佳答案

正如您所注意到的,这是修改 Array 原型(prototype)的结果。特别是因为方法 toString 用于数组和原始值之间的相等性检查。

通常,当您使用 == 时,其中一个操作数是一个对象,javascript 将尝试使用 the steps outlined in the ECMAScript Spec 将该对象转换为基本类型。 .第 3 部分和第 4 部分特别是:

  1. If hint is "string", then let methodNames be «"toString", "valueOf"».
  2. Else, Let methodNames be «"valueOf", "toString"».

如您所见,toString 方法将作为尝试将数组转换为基元的一部分被调用。默认情况下,数组 valueOf 方法不返回原语,并且由于您重写了 toString 方法,现在它不返回原语任何一个!因此,我们越过第 5 步,继续第 6 步:

  1. Throw a TypeError exception.

这是一个演示:

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 规范相结合的结果.

关于javascript - Firefox Javascript "can' t convert to a primitive type"错误是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59122309/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com