0

I'm trying to add an array to my existing array. This works in a strange way. The number of an array is added to the existing array, but all the existing arrays have their values changed to the value of the last added array :(

var BigArray = [];
var myArray = [];

function clickBtn(){
  myArray["fixedName"] = Math.random() * 5;
  addArray();
}

function addArray() {
  BigArray = BigArray.concat([myArray]);
  console.log(BigArray);
}
<button onclick="clickBtn()">click me</button>

It will be added after a few clicks on the button. Although all data is different, all arrays added to BigArray are the same!

nego
  • 23
  • 4
  • You're adding the same array again. You only have one `aArray`, and adding it multiple times to `BigArray` does not make copies of that array. So any later mutation of that `aArray` will be seen in `BigArray`. – trincot Mar 10 '23 at 09:04
  • Aside from the issue that you're reusing the same array object, this code is suspect: `aArray["fixedName"] = data;` That's adding a `fixedName` property to the array object. While you *can* do that in JS (since arrays are objects), it's unusual. Normally you only use an array when you want to use array-specific features. In the code above, you aren't using array features w/`aArray`. It should probably just be an object (`let aObject = = {};`) or a `Map` (more about picking which [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps)). – T.J. Crowder Mar 10 '23 at 09:10

0 Answers0