为什么console.log(Firefox)会显示带有直括号的对象?

问题描述 投票:1回答:1

我已经搜索了许多现有主题,但没有一个具体到足以确切指出我怀疑的地方。只是为了学习。我创建了一个构造函数,其唯一目的是将它用作函数Array的目标(显然创建一个数组),然后使用与'normal'构造函数相同的函数和'new'关键字。

function Myray(val0,val1,val2){ 
this[0] = val0;
this[1] = val1;
this[2] = val2;
}
// Not using the 'new' keyword, but the function Array.
var res = Array.call(Myray, 'one', 'two', 'three');

console.log(res);  -->  Array(3) [ "one", "two", "three" ]
console.log(Array.isArray(res));  //  -->  true

现在,通常在同一构造函数上使用'new'关键字,按预期生成一个对象,但在直括号之间显示为数组对象。

function Myray(val0,val1,val2){ 
this[0] = val0;
this[1] = val1;
this[2] = val2;
}
var res2 = new Myray('one','two','three');
console.log(res2);  -->  Object(3) [ "one", "two", "three" ]

问题是,如果功能相同。使用Array.call调用函数时,Array只关心查看它所调用的对象,设置继承链并创建其结果数据类型,在本例中为数组。第二个调用函数Object不应该这样做吗?为什么显示在直括号中?

javascript constructor prototype
1个回答
0
投票

考虑到构造函数具有整数索引属性,我将根据Bergi的猜测,浏览器的控制台可以随意格式化。原因是如果在Node.js终端中运行代码,它会在大括号之间显示结果,因此确认了Bergi的意见。我之前应该这样做...谢谢大家。

© www.soinside.com 2019 - 2024. All rights reserved.