gpt4 book ai didi

javascript - 对象的 getFullYear()

转载 作者:行者123 更新时间:2023-12-01 01:27:33 25 4
gpt4 key购买 nike

不确定标题,但我对对象文字值有疑问。我有一个名为“人”的对象,其中包含名字、姓氏、国籍和出生。当我初始化它时,我将一些值带入对象中,“出生”值以“YYYY-MM-DD”的形式出现,但我必须提供全年“YYYY”。

let person = {
firstName: '',
lastName: '',
nationality: '',
born: '',

print3: function() {
return 'My name is ' + this.firstName + ' ' + this.lastName + ' from ' + this.nationality + '.' + ' I was born ' + this.born + '.';
},

init: function(firstName, lastName, nationality, born) {
this.firstName = firstName;
this.lastName = lastName;
this.nationality = nationality;
this.born = born;
}
};

初始化:

person2.init('Henri', 'Becquerel', 'France', '1852-12-15')

预期结果应该是:

"My name is Henri Becquerel from France. I was born 1852."

我知道我必须在代码中的某个地方使用 .getFullYear 函数,但我已经尝试了所有我能想到的地方,但我没有想法。

问候

最佳答案

new Date() 将像您一样解析 ISO 8601 格式的字符串。因此,您的 init() 函数可以保存日期对象而不是字符串。然后你可以在 this.born 上调用 getFullYear():

let person = {
firstName: '',
lastName: '',
nationality: '',
born: '',

print3: function() {
return 'My name is ' + this.firstName + ' ' + this.lastName + ' from ' + this.nationality + '.' + ' I was born ' + this.born.getFullYear() + '.';
},

init: function(firstName, lastName, nationality, born) {
this.firstName = firstName;
this.lastName = lastName;
this.nationality = nationality;
this.born = new Date(born); // create a Date object
}
};

person.init('Henri', 'Becquerel', 'France', '1852-12-15')
console.log(person.print3())

关于javascript - 对象的 getFullYear(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com