I have an array in which all the elements are also arrays (of integers), called mainArray.
I am trying to use splice() to add and remove its elements (subarrays).
Initially mainArray has a single element (an Array with one integer), I wish to delete it and add 3 new subarrays to mainArray, these are defined in arraysToAdd.
mainArray = new Array(new Array(1));
arraysToAdd = new Array(new Array(1,2), new Array(1,4), new Array(1,7));
alert(arraysToAdd.length); // Returns: 3: as expected
mainArray.splice(0,1,arraysToAdd);
alert(mainArray.length); // Returns: 1: I want this to be 3
I expect the length of mainArray at the end to be 3 (as it should contain 3 subarrays), but it seems splice() is flattening arraysToAdd and so mainArray ends up just being an array of integers.
What am I missing?
console.log(mainArray)splice()is flatteningarraysToAdd" Uhm, how can the length ofmainArraybe1if the other arrays is flattened intomainArray? IfmainArraywas an array of integers, wouldn't the length be 6?var mainArray = [[1]];, right?mainArrayworked because you didn't use the value, but if you had tried to use it, or if you created it with a greater number, you'd get a result that you may not expect. Like if you didnew Array(3), you now have an Array with.length === 3, and no actual defined members.