Reputation: 65510
Please could someone tell me why this operation changes the value of the original array?
var today = new Date();
var max_x_domain = [today];
var one_year_after_end = max_x_domain.slice(0)[0];
one_year_after_end.setYear(one_year_after_end.getFullYear() - 1);
console.log('array after operation', max_x_domain);
And how can I make a copy of max_x_domain[1]
... do I need to use a clone method as described here?
This is... a surprising feature of JavaScript.
Upvotes: 1
Views: 103
Reputation: 5015
when using slice
you create a copy and therefor a new array, without modifying the original. But the Elements inside are not copied/cloned, unless they are of a primitive type (bool, string, number). Since you have a Date Object in there, there will be a new array created but the same reference to your date object will be 'copied'. Thus, if you want to have an fresh Date Object, do new Date(oldDate)
/ var one_year_after_end=new Date(max_x_domain.slice(0)[0])
and you can modify it from there on without modifying the original Date Object.
Upvotes: 1
Reputation: 38345
It's not at all surprising if you consider that your array contains object references. As this section of the MDN docs states:
For object references (and not the actual object),
slice
copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
Upvotes: 3
Reputation: 9576
var dateToCopy = new Date();
var newDate = new Date(dateToCopy);
Refactored code
var today = new Date();
var max_x_domain = [today];
var one_year_after_end = new Date(max_x_domain.slice(0)[0]);
one_year_after_end.setYear(one_year_after_end.getFullYear() - 1);
console.log('array after operation', max_x_domain);
Upvotes: 1