I want to replace the entire object in an array.
http://jsfiddle.net/CWSbJ/
var array = [ {name: "name1" }, { name: "name2" } ];
var element = array[0];
element = {name: "name3"};
alert(array[0].name);
In this piece of code I would expect the output name3, why can't I replace an entire object in an array like this? And what is the good way to do this?
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
We can use the splice() method to replace a part of array elements with elements from another array. But in this scenario we need to pass the elements as parameters, not the array as parameter. To achieve the above task splice() method except the parameters like (0, anotherArr. Length, 1, 2, 3).
std::replace and std::replace_if in C++void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) first, last : Forward iterators to the initial and final positions in a sequence of elements. old_value : Value to be replaced. new_value : Replacement value.
The correct way is
array[0] = {name: "name3"};
Your existing code does not work as expected because you are taking a referenc* to the first element with
var element = array[0];
and then you are replacing the value of this local variable with another object. This leaves the original array unmodified.
Try this :
var array = [ {name: "name1" }, { name: "name2" } ];
array[0] = {name: "name3"};
alert(array[0].name);
element
is not the actual array - its a copy of the array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With