2017-06-03 66 views
0

我有以下代碼創建一個新的對象:問題與新的日期

function Person(firstname, lastname, birth) { 
 
this.name = firstname + " " + lastname; 
 
this.bdate = { 
 
\t year: birth.getFullYear(), 
 
\t day: birth.getDate(), 
 
\t month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth() - 1], 
 
\t monthnumber: birth.getMonth(), 
 
\t } 
 
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對象。

這是在控制檯執行FOO當我得到什麼:

foo 
Object { name: "Jon Doe", bdate: Object, age: 20 } 

當我bdate對象 點擊我得到:

month: undefined 

如何解決? PLUS一年是1997年,而不是1996年

編輯:不,這不是重複getutcmonth的是,這個問題是治療12爲0,礦山返回未定義月

ANOTHER編輯:呵呵,我想這acually是重複的: P仍然,你能幫助我嗎?

+2

'12'不是有效的月份。如果你想要十二月,它應該是'新日期(1996,11,5)'。 – Xufox

+1

[Javascript getUTCMonth()返回0可能重複12月?](https://stackoverflow.com/questions/8335276/javascript-getutcmonth-returns-0-for-december) – Xufox

回答

0

月份爲零。所以你的數組偏移是錯誤的,並且該月份必須增加/減少。

function Person(firstname, lastname, birth) { 
 
this.name = firstname + " " + lastname; 
 
this.bdate = { 
 
\t year: birth.getFullYear(), 
 
\t day: birth.getDate(), 
 
\t month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth()], 
 
\t monthnumber: birth.getMonth()+1, 
 
\t } 
 
this.age = new Date().getFullYear() - birth.getFullYear(); 
 
} 
 

 
var foo = new Person("Jon", "Doe", new Date(1996, 11, 5)); 
 
console.log(foo);

+0

有沒有辦法總是減少/增加月?像「新日期(1996,12,5)」變成「新日期(1996,11,5)」? – adddff

+0

@adddff從現有日期開始時,使用setMonth來表示;構成日期的組件的設置方法考慮到了「溢出」內置。 – CBroe

+0

@adddff您可以傳遞值而不是Date對象,然後在構造函數中生成日期,偏移量爲 –