我正在学习有关Udemy的课程,但我听不懂下面的代码。我想知道
 代码底部的功能calcAverage(tips)可以从john和mark对象访问属性提示。



var john = {
    fullName: 'John Smith',
    bills: [124, 48, 268, 180, 42],
    calcTips: function() {
        this.tips = [];
        this.finalValues = [];

        for (var i = 0; i < this.bills.length; i++) {
            // Determine percentage based on tipping rules
            var percentage;
            var bill = this.bills[i];

            if (bill < 50) {
                percentage = .2;
            } else if (bill >= 50 && bill < 200) {
                percentage = .15;
            } else {
                percentage = .1;
            }

            // Add results to the corresponing arrays
            this.tips[i] = bill * percentage;
            this.finalValues[i] = bill + bill * percentage;
        }
    }
}

var mark = {
    fullName: 'Mark Miller',
    bills: [77, 475, 110, 45],
    calcTips: function() {
        this.tips = [];
        this.finalValues = [];

        for (var i = 0; i < this.bills.length; i++) {
            // Determine percentage based on tipping rules
            var percentage;
            var bill = this.bills[i];

            if (bill < 100) {
                percentage = .2;
            } else if (bill >= 100 && bill < 300) {
                percentage = .1;
            } else {
                percentage = .25;
            }

            // Add results to the corresponing arrays
            this.tips[i] = bill * percentage;
            this.finalValues[i] = bill + bill * percentage;
        }
    }
}

function calcAverage(tips) {
    var sum = 0;
    for (var i = 0; i < tips.length; i++) {
        sum = sum + tips[i];
    }
    return sum / tips.length;
}

最佳答案

calcAverage对对象markjohn一无所知。它只是一个将数组作为参数的函数。它将计算传入的数组的平均值:



var mark = {
  fullName: 'Mark Miller',
  bills: [77, 475, 110, 45],
  calcTips: function() {
      this.tips = [];
      this.finalValues = [];

      for (var i = 0; i < this.bills.length; i++) {
          // Determine percentage based on tipping rules
          var percentage;
          var bill = this.bills[i];

          if (bill < 100) {
              percentage = .2;
          } else if (bill >= 100 && bill < 300) {
              percentage = .1;
          } else {
              percentage = .25;
          }

          // Add results to the corresponing arrays
          this.tips[i] = bill * percentage;
          this.finalValues[i] = bill + bill * percentage;
      }
  }
}

function calcAverage(tips) {
  var sum = 0;
  for (var i = 0; i < tips.length; i++) {
      sum = sum + tips[i];
  }
  return sum / tips.length;
}

mark.calcTips() // calculates tips and store as tips property

// pass mark.tips into function
console.log("Mark's tip average:", calcAverage(mark.tips))

关于javascript - 函数calcAverage如何返回(提示)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53355782/

10-11 11:29