简体   繁体   中英

Array referencing: adding an object to array of objects

This is probably a very basic question - see a simple code:

var ar1=[];
var ar2=[];
ar1[0] = 'Constant';
ar1[1] = data.attr.const;
ar2.push(ar1);  //OK, ar2 contains one array of two correct elements

ar1[0] = 'R-squared';
ar1[1] = data.attr.rsq;
ar2.push(ar1);   // Not OK - ar2 contains 2 identical arrays

ar1[0] = 'R-sq. adjusted';
ar1[1] = data.attr.rsqadj;
ar2.push(ar1);   // Not OK - ar2 contains 3 identical arrays

The problem is that every time when it executes ar2.push(ar1) , it overwrites all elements of ar2. After this code is executed, I get an obect with containing 3 identical arrays. How can I fix it?

Thanks

Objects in JS are always references (unlike strings or numbers). Whenever you push you're referring to the same object that is already inside the array, you need to clone:

ar2.push(ar1.slice(0)); // clone ar1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM