我有以下代码创建一个新对象:
function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
year: birth.getFullYear(),
day: birth.getDate(),
month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth() - 1],
monthnumber: birth.getMonth(),
}
this.age = new Date().getFullYear() - birth.getFullYear();
}
var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
console.log(foo);

当我执行以下代码时:
var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
它完全应该做的事情:创建一个新的Person对象。
BUT
这是我在控制台做foo时得到的结果:
foo
Object { name: "Jon Doe", bdate: Object, age: 20 }
当我点击bdate对象时 我明白了:
month: undefined
如何修复? PLUS年份是1997年而不是1996年
编辑:不,它不是getutcmonth的副本,那个问题是处理12 AS 0,我的返回未定义月份
另一个编辑:嗯,我猜它真的是重复的:P还在,你能帮助我吗?
答案 0 :(得分:0)
月份从零开始。因此,您的Array偏移是错误的,并且必须增加/减少月份。
function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
year: birth.getFullYear(),
day: birth.getDate(),
month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth()],
monthnumber: birth.getMonth()+1,
}
this.age = new Date().getFullYear() - birth.getFullYear();
}
var foo = new Person("Jon", "Doe", new Date(1996, 11, 5));
console.log(foo);