javascript - MomentJS possible bug with the add() function -


i'd add several months in array cannot add() function of momentjs work properly. here's how goes :

    function getmonths(begin, end){         var cursor = moment(begin);         var momentend = moment(end);         var arraymonths = [];         while(cursor.month() != momentend.month() || cursor.year() != momentend.year()){                     cursor.add(1, 'month'); // adds 1 month cursor             console.log(cursor.todate()); // because display cursor added month             arraymonths.push(cursor.todate()); // cursor being pushed doesn't have added month             console.log(arraymonths); // verified here         }                return arraymonths;     } 

the console log shows cursor has been incremented (as add() mutator) proper value isn't added array.

i cannot figure out if issue in code or if inherent momentjs. have clue ?

thank !

the documentation todate says:

to native date object moment.js wraps, use moment#todate.

this return date moment uses, changes date cause moment change. if want date copy, use moment#clone before use moment#todate.

ie you're getting the same underlying date object every time call todate - ie each call add modifying it, , every member of array same object.

if documentation says, , use clone, code works:

arraymonths.push(cursor.clone().todate()); 

here's demo:

function getmonths(begin, end){    var cursor = moment(begin);    var momentend = moment(end);    var arraymonths = [];    while(cursor.month() != momentend.month() || cursor.year() != momentend.year()){              cursor.add(1, 'month'); // adds 1 month cursor      console.log(cursor.todate()); // because display cursor added month            //clone object before pushing, ensure it's not further modified      arraymonths.push(cursor.clone().todate());             console.log(arraymonths); // verified here    }           return arraymonths;  }              getmonths(moment('2016/01/01', 'yyyy/mm/dd'), moment('2017/01/01', 'yyyy/mm/dd'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -