javascript - JavaScript 对象操作的问题
问题描述
我是 JavaScript 新手,我在使用对象中的outputallCustomers
函数时遇到了一些问题。CustomerDB
我可以输出所有客户数据(硬编码并插入到此处未包含的函数中的对象中),但对该getAddressbyId
函数的调用无法正常工作,我不知道为什么。
var CustomerDB = {
customers: [],
addresses: [],
stores: [],
addCustomer: function (customerObj) {
customerObj.add_date = new Date ();
this.customers.push(customerObj);
},
outputAllCustomers:function () {
console.log("All Customers\n");
for (var i=0;i < this.customers.length;i++) {
console.log("Customer " + this.customers[i].customer_id + ": " + this.customers[i].first_name + " " + this.customers[i].last_name + " (" + this.customers[i].email + ")");
var customerAddress = this.getAddressById(this.customers[i].address_id);
console.log("Home Address: " + customerAddress.address + " " + customerAddress.city + " " + customerAddress.province + " " + "." +customerAddress.postal_code);
break;
}
},
/***********************************
* adress methods *
* **********************************/
addAddress : function (addressObj) {
this.addresses.push(addressObj);
},
getAddressById : function (address_id) {
var result;
for (var i = 0;i < this.addresses.length;i++) {
if (this.addresses[i].address_id == address_id) {
result = this.addresses[i];
console.log(this.addresses[i].address_id);
}
return result;
}
},
}
解决方案
尝试下一个解决方案
var CustomerDB = {
customers: [],
addresses: [],
stores: [],
addCustomer: function (customerObj) {
customerObj.add_date = new Date();
this.customers.push(customerObj);
},
outputAllCustomers: function () {
console.log("All Customers\n");
for (var i = 0; i < this.customers.length; i++) {
console.log("Customer " + this.customers[i].customer_id + ": " + this.customers[i].first_name + " " + this.customers[i].last_name + " (" + this.customers[i].email + ")");
var customerAddress = this.getAddressById(this.customers[i].address_id);
console.log("Home Address: " + customerAddress.address + " " + customerAddress.city + " " + customerAddress.province + " " + "." + customerAddress.postal_code);
break;
}
},
/***********************************
* adress methods *
* **********************************/
addAddress: function (addressObj) {
this.addresses.push(addressObj);
},
getAddressById: function (address_id) {
var result;
for (var i = 0; i < this.addresses.length; i++) {
if (this.addresses[i].address_id == address_id) {
result = this.addresses[i];
console.log(this.addresses[i].address_id);
return result;
}
}
// Return not found
return false;
},
}
推荐阅读
- java - 使用 Pyjnius 覆盖 Python 中的 Java 方法
- vba - InStr VBA区分上下字符
- xamarin.forms - 使用 Xamarin Forms 创建动态表单
- c# - 使用 EF Core 和 DI 登录 Azure Functions
- javascript - 在给定坐标的地图上绘制点与openlayers?
- here-api - 如何在 Here.com Maps for javascript API 3.1 中突出显示标记?
- vue.js - 如何读取vue中文件的特定目录
- c++ - 为什么 std::is_invocable 不能处理转发?
- r - 是否有 R 函数来检索 CPU 和 RAM 信息?
- r - dplyr 等效于 in