我正在学习Javascript,我遇到了一些小问题。这是我在这里的第一篇帖子,请帮助我理解:
-
为什么一个数字(例如:2024)减去我的javascript对象属性“this.birthYear”(例如:1995,显然是一个数字)会返回Not a number(NaN)?这可能是我浏览器控制台的解析错误吗?
-
如果这是我的错误,我需要在代码中更改什么才能使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)。