我正在创建一个Web应用程序,并且具有以下内容:
this.arr = [];
(async function f() {
try {
const response = await this.myService.getData();
const data = response.data;
data.forEach((entry) => {
this.arr.push(new MyObject(entry.valueOne, entry.valueTwo));
});
} catch (error) {
console.log(error);
}
}).call(this);
现在,当我查询this.arr
时,将得到以下输出:
[]
0: Object { valueOne: "foo", valueTwo: "bar" }
1: Object { valueOne: "foobar", valueTwo: "foo" }
length: 2
<prototype>: Array []
因此,尝试仅通过记录第一个元素
this.console.log(this.arr[0]);
我明白了
TypeError: this.arr[0] is undefined
我认为问题在于,我将元素推入一个空数组,因为当我像这样手动创建数组时
console.log(
[
{name: "foo", description: "bar"},
{name: "foobar", description: "foo"},
]
);
我得到以下输出:
(2) […]
0: Object { name: "foo", description: "bar"}
1: Object { name: "foobar", description: "foo"}
length: 2
<prototype>: Array []
几乎相同,除了手动生成的数组的长度显示在方括号中。