首页 > 解决方案 > 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;
        }
      },
    }

标签: javascript

解决方案


尝试下一个解决方案

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;
  },
}

推荐阅读