Section 2.8: CODDING CHALLENGE 3

使用对象和方法计算BMI
本文介绍了一种使用JavaScript对象和方法来计算并比较两个人BMI(身体质量指数)的方法。通过创建包含姓名、体重和身高的对象,并为每个对象添加计算BMI的方法,最后比较并输出BMI较高的个体。

Let’s remember the first coding challenge where Mark and John compared their BMI. Let’s now implement the same functionality with objects and methods.

  1. for each of them, create an object with properties for their full name mass, and height.
  2. then, add a method to each object to calculate the BMI. Save the BMI to the object and also return it from the method.
  3. In the end, log to the console who has the highest BMI, together with the full name and the respectiove BMI. Don’t forget they might have the same BMI.

Remember: BMI = mass / height^2 = mass / (height *height).

Good Luck

var john = {
    fullName: 'John Smith',
    mass: 92,
    height: 1.95,
    calculateBMI: function () {
        this.bmi = this.mass / (this.height * this.height) // this.bim is where we store it.
        return this.bmi;
    }
}

var mark = {
    fullName: 'Mark Miller',
    mass: 78,
    height: 1.69,
    calculateBMI: function () {
        this.bmi = this.mass / (this.height * this.height) // this.bim is where we store it.
        return this.bmi;
    }
}

john.calculateBMI();
mark.calculateBMI();
console.log(john, mark);


//never repeat yourself!!! but for this section is the best way to understand. we will learn it in the future.

if (john.bmi > mark.bmi) {
    console.log(john.fullName + ' has a higher BMI of ' + john.bmi);
} else if (mark.calculateBMI() > john.calculateBMI()) { //or we can just call the function to get the BMI
    console.log(mark.fullName + ' has a higher BMI of ' + mark.bmi);
} else {
    console.log('They have the same BMI of ' + john.bmi)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值