不确定标题,但是对象文字值有问题。我有一个名为'person'的对象,具有姓,名,国籍和出生日期。初始化此对象时,我会在对象中携带一些值,并且“出生”值以“ 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函数,但是我已经尝试了所有可以想到的地方,但我没主意。
致谢
答案 0 :(得分:2)
new Date()
将像您一样解析ISO 8601格式的字符串。因此,您的init()
函数可以保存日期对象而不是字符串。然后,您可以在getFullYear()
上致电this.born
:
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())
答案 1 :(得分:0)
只需创建日期的实例,然后在其上调用getFullYear()。
那将是:new Date('1852-12-15')。getFullYear()