Javascript 类的Array.map()给出了未定义的
我试图使用数组的map函数将数据映射到特定的类。这项工程正在进行中 因此,我:Javascript 类的Array.map()给出了未定义的,javascript,arrays,Javascript,Arrays,我试图使用数组的map函数将数据映射到特定的类。这项工程正在进行中 因此,我: me.$http({ url: me.appConfig.api + `customer/${customer.number}/stock/warehouses`, method: 'get' }).then((r: any) => { def.resolve(r.data.map(Warehouse)); }).catch(def.reject); 到目前为止相当基本。然后在我的仓库
me.$http({
url: me.appConfig.api + `customer/${customer.number}/stock/warehouses`,
method: 'get'
}).then((r: any) => {
def.resolve(r.data.map(Warehouse));
}).catch(def.reject);
到目前为止相当基本。然后在我的仓库类中,它看起来像这样:
export class Warehouse {
code: string;
location: string;
weight: number;
count: number;
late: number;
stock?: Stock[];
constructor(data?: any) {
console.debug('test', data);
this.code = 'test';
if (data) {
this.code = data.code;
this.location = data.location;
this.weight = data.weight;
this.count = data.count;
this.late = data.late;
}
}
}
所以只是一个值的副本,但奇怪的是,它已经在this.code='test'
上出错了,然后我得到了错误:
TypeError: Cannot set property 'code' of undefined
at Warehouse (main.bundle.js:2218:19)
at Array.map (native)
你知道为什么会这样吗
样本数据:
[
{
"code": "SQD",
"location": "35,16161;6,31561",
"weight": 3200,
"count": 18,
"late": 18
},
{
"code": "GQZ",
"location": "35,16161;6,31561",
"weight": 321,
"count": 20,
"late": 18
}
]
您似乎正在向数组映射函数传递构造函数,这可能不是您想要的
def.resolve(r.data.map(Warehouse));
应该是
def.resolve(new Warehouse(r.data));
函数r.data.map(FN)接受一个函数并返回一个数组,该数组是从r.data的每个元素E中获取并调用以E为参数的函数得到的,如在FN(E)中。请参见您似乎正在向数组映射函数传递构造函数,这可能不是您想要的
def.resolve(r.data.map(Warehouse));
应该是
def.resolve(new Warehouse(r.data));
函数r.data.map(FN)接受一个函数并返回一个数组,该数组是从r.data的每个元素E中获取并调用以E为参数的函数得到的,如在FN(E)中。请参见能否共享样本
数据
?另外,我想问题在于这个而不是数据是的,问题在于“这个”,这就是为什么我做了这个.code='test'
,这在我的理解中是失败的,你必须这样做.map(x=>newwarehouse(x))
我想既然你是在传递一个构造函数,而不是一个对象,此
在该上下文中不存在。您的地图仅调用仓库,您需要使用新仓库构建新对象您可以共享示例数据
?另外,我想问题在于这个而不是数据是的,问题在于“这个”,这就是为什么我做了这个.code='test'
,这在我的理解中是失败的,你必须这样做.map(x=>newwarehouse(x))
我想既然你是在传递一个构造函数,而不是一个对象,此
在该上下文中不存在。您的映射只是调用warehouse,您需要使用new warehouse构建一个新对象我假设您根本不需要映射函数,因为您的构造函数基本上需要一个数据对象,并且已经在其中进行了深度复制。这不是我想要的,因为我希望每个r.data
都是仓库类型;)在这种情况下,Rajesh的评论可能就是您想要的,我假设您根本不需要map函数,因为您的构造函数基本上需要一个数据对象,并且已经在其中进行了深度复制。这不是我想要的,因为我希望每个r.data
都是Warehouse;)在这种情况下,拉杰什的评论可能是你想要的