This question already has answers here:
Copy array by value
(39 answers)
Closed 12 days ago.
I need to be able to record a previously existing variable in an array, and it should remain unchanged after the fact. The current problem is that whenever I set the variable to the value of another variable, it "follows" the value of the "reference variable". How can I prevent this from happening?
I have tried:
Pushing an empty new variable and setting it's value a line later to the variable that needs to be stored.
Pushing the variable as is into the array.
Using constants. This just froze the array and made me unable to record anything on it...
Sample code:
class dummy {
constructor (val1, val2) {
this.val1 = val1
this.val2 = val2
}
}
let data = []
let dummy1 = new dummy(1, 2)
data.push(new dummy(dummy1.val1, dummy1.val2)) // Keep in my that I have tried other ways of doing this.
dummy1.val1 = 3
dummy1.val2 = 4
console.log(dummy1)
console.log(data[0])
Desired output:
3, 4
1, 2
Current output:
3, 4
3, 4
Please, no alternatives to using an array.
Not sure if this would help,
You can make a variable immutable after changing it by using Object.freeze(). Object.freeze() is a method that prevents further changes to an object by making it read-only and non-configurable.
If your "var" is a object with plain properties, use this for pushing:
data.push({ ...dummy1 })
If not -contains other objects for example- then you need a deep copy as the others already said.
Related
This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 5 years ago.
Let's say we got this:
this.myObject = {"id":1};
and we want to store the state of my object as my object original as the following:
this.myObjectORG = this.myObject;
then you go on your business and change props on your object like this
this.myObject.id = 2;
and to your surprise down the road, you realize that
console.log (this.myObjectORG.id) // also reports 2
Well, that's just how JS works & I'm not questioning that.
Is there a way to preserve the state of the myObject so I can do comparisons whether its properties changed since its original state?
At some point I'd like to be able to do something like this
if ( this.myObjectORG.id !== this.myObject.id ) {
// but this condition is never true
}
Does this help:-
An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.
var this.myObjectORG = Object.assign({}, this.myObject);
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 4 months ago.
If I do
var a = [].push(undefined);
console.log(a);
it gives output as 1 even though undefined was pushed to the array. Any idea why?
You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:
var a = []
a.push(undefined);
console.log(a);
You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.
its pushing the length of array inside not the elements
example
var a = [].push(5,6,7,8);
console.log(a); //gives 4
Push returns the new length of the array, and thats what is stored in a
There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
Let setStatus be Set(O, ToString(len), E, true).
ReturnIfAbrupt(setStatus).
Let len be len+1.
You can see it here. Step 8.
This question already has answers here:
javascript pass by reference workaround
(2 answers)
Closed 6 years ago.
So i have an javascript object called gamewhich has two methods:
function game() {
this.TxtRevealed = new Array();
this.TxtRevealedBackup = new Array();
[...]
}
Now, outside an object i assign one two another:
game.TxtRevealedBackup = game.TxtRevealed;
After a while i change game.TxtRevealed(i use slice function to cut some values from it).
And now happens something i do not intend: automatically game.TxtRevealedBackup changes also to new value of game.TxtRevealed.
I'd expect that game.TxtRevealedBackup would be same as game.TxtRevealed was in moment of assigning. It works as if game.TxtRevealedBackup was pointing to value that is represented by game.TxtRevealed continously, not the value it was in moment of assignment.
Why is it happening and how to make it working i'd expect?
Kalreg.
Objects do work by reference. If you want to clone objects see this answer.
This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?
To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.
Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript a pass-by-reference or pass-by-value language?
In this file I have an object this.objectA and this.allAs;
this.objectA contains a few attributes.
Everytime I got a new this.objectA, I add it to the array this.allAs.
I always reassign this.objectA when I get a new one.
Later I check my array this.allAs, I found that it correctly stores different this.objectA.
How come this.objectA gets overwritten, the objects inside this.allAs didn't get overwritten? (I expect all those stored objects to to pointing to the same this.objectA, but it didn't) Javascript is pass by value for objects???
You've got to get a lot more specific about what you're doing.
JavaScript passes by reference, but if you're saving local copies anywhere, and copying those values from return statements, then you're not working from reference anymore -- they're no longer pointers to the exact same object, necessarily.
Here's something to demonstrate passing references:
Bob = { name : "Bob", age : 32 };
function giveBobTo (obj, bobject) { obj.bob = bobject; }
Billy = {};
Jim = {};
giveBobTo(Billy, Bob);
giveBobTo(Jim, Bob);
Jim.bob.cars_on_lawn = 8;
Billy.bob.cars_on_lawn; // 8;
Bob.cars_on_lawn; // 8;
console.log( "Billy-Bob equals Jim-Bob equals Bob:",
Billy.bob === Jim.bob === Bob); // true