为什么我的 Javascript 方法在计算两个数字类型时返回 NaN? [已关闭]

问题描述 投票:0回答:1

我正在学习 Javascript,遇到了一些问题。这是我在这里的第一篇文章,请帮助我理解:

  1. 为什么一个数字(例如:2024)减去我的 javascript 对象属性:'this.birthYear'(例如:1995,显然是一个数字)返回不是数字(NaN)?这可能是我的浏览器控制台的解析错误吗?
  2. 而且,如果这是我的错误,我需要在代码中更改哪些内容才能使 2024 - 1995 = 29?

这是我的代码:

const penguin = {
    firstName: 'Zachary',
    birthYear: 1995,
    job: 'Developer',
    friends: ['Michael', 'Joe', 'Evan'],
    hasDriversLicense: true,
    
    // methods
    calcAge: function () {
        this.age = 2024 - this.birthyear;
        return this.age;
    },

    getSummary: function () {
        this.hasDriversLicense ? this.getSummary = 'a' : this.getSummary = 'no';
        return this.getSummary;
    }
};

penguin.calcAge();
penguin.getSummary();

console.log(penguin.age); // why NaN ???
console.log(penguin.getSummary);

// summary

console.log(`${penguin.firstName} is a ${penguin.age} year-old ${penguin.job}, and he has ${penguin.getSummary} Driver's License.`);

Refer to screenshot for my output example.

提前谢谢您。

我尝试登录到我的浏览器控制台

console.log(penguin.age)
,它输出 NaN(但是,如果硬编码 1995 年的数字,我会得到预期结果:29)。

javascript parsing methods nan typeof
1个回答
0
投票

检查 calcAge 函数中 this.birthyear 的拼写,您希望它是 this.birthYear。

© www.soinside.com 2019 - 2024. All rights reserved.