JavaScript对象内函数方法失效?BMI计算功能异常排查
你的BMI计算代码问题排查
核心问题(和this无关,是这几个错误导致的)
- 属性值类型错误:
Mass和Height是带单位的字符串(比如"78 kg"),JavaScript无法直接对字符串执行数学运算,必须提取纯数值才能计算。 - 计算逻辑完全错误:你写的
this.Mass / this.Height ** 2 - this.Mass / (this.Height * this.Height)中,this.Height ** 2和this.Height * this.Height是等价的,相减结果永远是0,完全不符合BMI的计算公式(正确公式是体重(kg) / 身高(m)²)。 - 方法调用错误:你混淆了方法引用和方法执行——
john.calcBMI是函数本身,不是计算结果,必须加()调用(john.calcBMI())才能得到BMI值;而且你在console.log里混用了john.calcBMI(输出函数代码)和mark.calcBMI()(输出结果),导致输出混乱。
修正后的代码示例
const mark = { firstName: "Mark", lastName: "Miller", mass: 78, // 直接存储数值,去掉单位,属性名用小写更符合JS规范 height: 1.69, calcBMI: function () { // 计算BMI并存在对象属性里,避免重复计算 this.bmi = this.mass / (this.height ** 2); return this.bmi; }, }; const john = { firstName: "John", lastName: "Smith", mass: 92, height: 1.95, calcBMI: function () { this.bmi = this.mass / (this.height ** 2); return this.bmi; }, }; // 先调用方法计算BMI mark.calcBMI(); john.calcBMI(); // 比较并输出结果 if (john.bmi > mark.bmi) { console.log(`${john.firstName} has a BMI of ${john.bmi.toFixed(1)} which is higher than ${mark.firstName} who has a BMI of ${mark.bmi.toFixed(1)}`); } else { console.log(`${mark.firstName} has a BMI of ${mark.bmi.toFixed(1)} which is higher than ${john.firstName} who has a BMI of ${john.bmi.toFixed(1)}`); }
内容的提问来源于stack exchange,提问作者vitoria
相关产品推荐
相关产品推荐

