我给了一个大数组,然后我必须将数据传输到一个不同的数组,具体取决于类型是"客户" "存储"或"地址"但是我得到了以下错误;我不知道为什么
/*
Exception: ReferenceError: store is not defined
CustomerDB.insertData@Scratchpad/1:56:17
@Scratchpad/1:105:1
*/
var allData = [
{type:"store", data:{store_id: 297, name: "Scotiabank - Main Branch", address_id: 1023}},
{type:"store", data:{store_id: 614, name: "Scotiabank - Hamilton", address_id: 1984}},
{type:"customer", data:{customer_id: 24, store_id:614, first_name: "Jonathan", last_name: "Pym", email: "jjpym@yahoo.ca", address_id: 1611, add_date: null}},
{type:"customer", data:{customer_id: 36, store_id:193, first_name: "Kaitlyn", last_name: "Adams", email: "katy38@hotmail.com", address_id: 5464, add_date: null}},
{type:"customer", data:{customer_id: 73, store_id:297, first_name: "Melissa", last_name: "Bennett", email: "mbennett@gmail.com", address_id: 4536, add_date: null}},
{type:"address", data:{address_id: 1023, address: "2895 Yonge St.", city:"Toronto", province:"ON", postal_code:"L4C02G"}},
{type:"address", data:{address_id: 1984, address: "3611 Main St. West", city:"Hamilton", province:"ON", postal_code:"R5O8H5"}},
{type:"address", data:{address_id: 1757, address: "1177 Ontario St. Unit 8", city:"Mississauga", province:"ON", postal_code:"L9H6B3"}},
{type:"address", data:{address_id: 4536, address: "3945 John St.", city: "Ajax", province: "ON", postal_code: "L7M4T9"}},
var CustomerDB =
{
customer:[],
address:[],
store:[],
insertData:function (allData)
{
for (var i = 0; i < allData.length; i++)
{
if (allData[i].type == "store")
{
store[i].push(allData[i].store_id, allData[i].name, allData[i].address_id);
}
else if (allData[i].type == "customer")
{
this[i].add_date = new Date();
customer[i].push(allData[i].customer_id, allData[i].store_id, allData[i].first_name, allData[i].last_name, allData[i].email, allData[i].addess_id, allData[i].add_date);
}
else if (allData[i].type == "address")
{
address[i].push(allData[i].address_id, allData[i].address, allData[i].city, allData[i].province, allData[i].cpostal_code);
}
}
}
}
CustomerDB.insertData(allData);
答案 0 :(得分:0)
虽然我仍然认为https://stackoverflow.com/a/42182030/6647153是最好的答案。但是你走了:
this
关键字来访问属性(数组)store
,cutomer
和adress
。试试这个:
insertData: function (allData) {
for (var i = 0; i < allData.length; i++) {
if (allData[i].type == "store") {
this.store.push(allData[i]);
}
else if (allData[i].type == "customer") {
allData[i].add_date = new Date();
this.customer.push(allData[i]);
}
else if (allData[i].type == "address") {
this.adress(allData[i]);
}
}
}
如果要复制对象而不是按原始对象,请使用以下函数:
function clone(obj) {
var newObj = {};
for(var key in obj)
newObj[key] = obj[key];
return newObj;
}
并称之为:
insertData: function (allData) {
for (var i = 0; i < allData.length; i++) {
var o = clone(allData[i]);
var type = o.type;
delete o.type; // to remove the type if you want
if (type == "store") {
this.store.push(o);
}
else if (type == "customer") {
var o.add_date = new Date();
this.customer.push(o);
}
else if (type == "address") {
this.adress(o);
}
}
}