This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
It's really strange, I'm modifying one of the arrays and the other one gets modified! I found no way of making it work other than typing two times the array. What can I do?
function test(a,b,c,d)
{
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
var data0=data=[[1,2,3,4],[5,6,7,8]];
function construct(constructor,args)
{
function F(){return constructor.apply(this,args);}
F.prototype=constructor.prototype;
return new F();
}
for(var i=0,l=data.length;i<l;i++)
{
data[i]=construct(test,data[i]);
}
console.log(data0);
http://jsfiddle.net/mageek/3GNMC/2/
You are referencing the same items:
var data0=data=[[1,2,3,4],[5,6,7,8]];
(and as a side note - here data ends up on the global object as it isn't really declared, only data0 is)
If you want to generate two different arrays with identical items you can do this:
var data0 =[[1,2,3,4],[5,6,7,8]];
var data = [];
data = data.concat(data0);
or
data = data0.slice(0);
JavaScript will not copy arrays upon data0=data assignment, instead it will point both variables to the same object in memory. You need to actually clone the array fully, for example:
var data0 = data.slice(0);
Related
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I have one object
var a = {b:{c:{d:{e:1}}}}
I want to copy that object to another variable b, without passing a reference, so I try spread operator
var b = {...a}
It is not removing reference at a deep level, as I change the value in the object "a" it also changes the value in the object "b"
a.b.c.d.e = 2
console.log(b.b.c.d.e)
it give output 2 instead of 1
var a = {b:{c:{d:{e:1}}}};
var b = {...a};
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
How can I handle this issue
I've always done this to copy JSON objects. Works great IMO there may be a better way out there.
var a = {b:{c:{d:{e:1}}}};
var b = JSON.parse(JSON.stringify(a));
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
For instance if I construct a new object type and create a few objects
function website(name,users)
{
this.name = name;
this.users = users;
}
var goog = new website("goog", "3,000,000");
var fireFox = new website("fireFox", "1,000,000");
var ie = new website("ie", "10");
And I push them into an array
var websites = [];
websites.push(goog,fireFox,ie);
Is there a way I can access a property of each object in the array through a loop?
For instance
for (var i=0;var<websites.length;i++)
{
console.log(websites[0.name]);
}
I know this code doesn't work but I hope it clarifies what I'm trying to ask.
Thanks!
When you say
websites[0.name]
It will try to get 0's name property, which is not valid. So, you should access it like this
websites[i].name
websites[i] will refer to the WebSite object in the array, at the index i and you are getting the name property with the . operator.
Also, your loop variable should be used in the for loop's condition, like this
for (var i=0; i < websites.length; i++)
This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
I have objects in array as
var arr = [{'name':'one','age':24},{'name':'two','age':21}]
I have assigned this array to another variable var newVar = arr. Now I am changing value of an objects of newVar as newVar[0].age = 18, But change the value of object of newVar get reflected in arr(original data) as well. After change value in newVar, arr is
var arr = [{'name':'one','age':18},{'name':'two','age':21}]
I want original data should be independent of changing values of another variable holding same data. How can I get it with java script?
Javascript handles objects by reference. If you have to change value in just a object you should "clone" it. This way there will be two different objects.
How to clone a object:
What is the most efficient way to deep clone an object in JavaScript?
use new Array().
var arr = [{'name':'one','age':24},{'name':'two','age':21}];
var newArr=new Array(arr);
To copy an array you would use slice. Unfortunately slice makes only a shallow copy. To make a deep clone you can use map method + $.extend to clone object:
var arr = [{'name':'one','age':24},{'name':'two','age':21}]
var newArr = arr.map(function(el) {
return $.extend({}, el);
});
newArr[0].name = 'TEST'
console.log(newArr[0].name, arr[0].name); // TEST one
Or it can be event shorter using some javascript magic:
var newArr = arr.map($.extend.bind(null, {}));
Result is the same.
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