简体   繁体   English

数组引用:将对象添加到对象数组

[英]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. 问题在于,每次执行ar2.push(ar1)时 ,都会覆盖ar2的所有元素。 After this code is executed, I get an obect with containing 3 identical arrays. 执行此代码后,我得到一个包含3个相同数组的对象。 How can I fix it? 我该如何解决?

Thanks 谢谢

Objects in JS are always references (unlike strings or numbers). JS中的对象始终是引用(不同于字符串或数字)。 Whenever you push you're referring to the same object that is already inside the array, you need to clone: 每当您push您都指的是数组中已经存在的同一对象,则需要克隆:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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