You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象比较练习遇阻,求comparePay方法修正方案

解决方法

你需要修正comparePay方法里的逻辑错误,确保正确引用调用对象与传入对象的属性、计算薪资差值并输出符合要求的结果。以下是完整的可运行实现:

1. 实现符合要求的Person对象

可以用构造函数批量创建实例,也直接用对象字面量定义,这里提供构造函数的简洁实现:

// 定义Person构造函数
function Person(name, occupation, pay) {
  this.name = name;
  this.occupation = occupation;
  this.pay = pay;

  // 修正后的薪资对比方法
  this.comparePay = function(person) {
    const payGap = this.pay - person.pay;
    if (payGap > 0) {
      console.log(`${this.name} earns ${payGap} more than ${person.name}`);
    } else if (payGap < 0) {
      console.log(`${this.name} earns ${Math.abs(payGap)} less than ${person.name}`);
    } else {
      console.log(`${this.name} and ${person.name} have the same salary`);
    }
  };

  // 输出对象详情的方法(整合你已实现的部分)
  this.showInfo = function() {
    console.log(`Name: ${this.name}, Occupation: ${this.occupation}, Pay: ${this.pay}`);
  };
}

// 创建指定的三个实例
const michael = new Person("Michael", "JS-programmer", 5000);
const lena = new Person("Lena", "Python-programmer", 1500);
const brad = new Person("Brad", "Teacher", 800);

2. 按要求执行输出流程

先输出所有对象详情,再执行薪资对比:

// 第一步:输出对象详情
michael.showInfo();
lena.showInfo();
brad.showInfo();

// 第二步:执行薪资对比(对应不可编辑的灰色调用代码)
michael.comparePay(lena);
lena.comparePay(brad);
brad.comparePay(michael);

3. 关键错误修正点

  • 属性引用修正:用this.name/this.pay指代调用对象的属性,用person.name/person.pay指代传入对象的属性,避免变量名写错。
  • 差值计算修正:正确计算this.pay - person.pay,通过差值正负判断薪资高低。
  • 输出逻辑修正:用Math.abs()处理负差值,保证输出的薪资差是正数,符合自然语言描述。

预期控制台输出

Name: Michael, Occupation: JS-programmer, Pay: 5000
Name: Lena, Occupation: Python-programmer, Pay: 1500
Name: Brad, Occupation: Teacher, Pay: 800
Michael earns 3500 more than Lena
Lena earns 700 more than Brad
Brad earns 4200 less than Michael

内容的提问来源于stack exchange,提问作者H. Ach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:47:54