- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的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 部分特别是:
- If hint is "string", then let methodNames be «"toString", "valueOf"».
- Else, Let methodNames be «"valueOf", "toString"».
如您所见,toString
方法将作为尝试将数组转换为基元的一部分被调用。默认情况下,数组 valueOf
方法不返回原语,并且由于您重写了 toString
方法,现在它不返回原语任何一个!因此,我们越过第 5 步,继续第 6 步:
- 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/
我是一名优秀的程序员,十分优秀!