admin 管理员组文章数量: 1086019
I have a function that should return two variables, thisYear
and nextYear
when I pass a date to the function. However, when I call .add
on date
it is changing the value of thisYear
even though thisYear
was already set.
Function and call
/
var someDate = moment()
thisYearAndNextYear(someDate)
function thisYearAndNextYear(date) {
const thisYear = date
console.log("thisYear = " + thisYear);
const nextYear = date.add(1, 'year')
console.log("nextYear = " + nextYear);
console.log("thisYear (after nextYear set) = " + thisYear);
}
Output
thisYear = 1522021438255
nextYear = 1553557438255
thisYear (after nextYear set) = 1553557438255 // ISSUE: this should still be 1522021438255
Does anyone understand how to prevent this odd behavior such that thisYear
retains its initial value?
I have a function that should return two variables, thisYear
and nextYear
when I pass a date to the function. However, when I call .add
on date
it is changing the value of thisYear
even though thisYear
was already set.
Function and call
http://jsfiddle/rLjQx/29945/
var someDate = moment()
thisYearAndNextYear(someDate)
function thisYearAndNextYear(date) {
const thisYear = date
console.log("thisYear = " + thisYear);
const nextYear = date.add(1, 'year')
console.log("nextYear = " + nextYear);
console.log("thisYear (after nextYear set) = " + thisYear);
}
Output
thisYear = 1522021438255
nextYear = 1553557438255
thisYear (after nextYear set) = 1553557438255 // ISSUE: this should still be 1522021438255
Does anyone understand how to prevent this odd behavior such that thisYear
retains its initial value?
- That is how moment works. It has cloning options, but if you want a library that never modifies your dates, you might check out date-fp. – Scott Sauyet Commented Mar 26, 2018 at 0:15
1 Answer
Reset to default 13Objects are passed by reference. When you pass an variable referencing an object to a function, that function still gets a reference to the original object. You can think of it like this: variables for non-primitives (such as objects) reference memory addresses, and those memory addresses get passed around.
So, when you call add
on the moment object, the object gets mutated.
If you want to clone the moment object so you can operate on a copy of it:
https://momentjs./docs/#/parsing/moment-clone/
call the .clone()
method.
const nextYear = date.clone();
nextYear.add(1, 'year')
本文标签: javascriptmoment()add changes previously set variableStack Overflow
版权声明:本文标题:javascript - moment().add changes previously set variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744000687a2516388.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论