Good day. Array:

var cap = [ ['a', 'b', 'c', 1], ['a', 'q', 'c', 0] ]; 

It is necessary to add an element equal to the last current to the end of the array, while changing the current value of 0 to 1, i.e. get the view:

  cap = [ ['a', 'b', 'c', 1], ['a', 'q', 'c', 1], ['a', 'q', 'c', 0] ]; 

I do this:

 cap.push(cap[cap.length-1]); cap[cap.length-1][3]= 1; 

but I get all the units at the end. Correct, please. Thank.


PS


The first line changed to:

 cap[cap.length] = cap[cap.length-1]; 

same result instead

  cap = [ ['a', 'b', 'c', 1], ['a', 'q', 'c', 1], ['a', 'q', 'c', 0] ]; 

I get:

  cap = [ ['a', 'b', 'c', 1], ['a', 'q', 'c', 1], ['a', 'q', 'c', 1] ]; 

UPD_2 I think the problem is that I insert the element not as an array, I did this:

 cap[cap.length] = '['+cap[cap.length-1]+']'; 

also some kind of curvature, but with numbers 0 and 1 here is already ok ...

  • So why do you add 1 to the last element, you need 0 cap [cap.length-1] [3] = 1; - vihtor
  • When I put 0, I get an alert: cap = a, b, c, 1, a, q, c, 0, a, q, c, 0 - Alex
  • Did you get: cap = a, b, c, 1, a, q, c, 1, a, q, c, 0? - Alex
  • Thanks for the help. - Alex

1 answer 1

In the cap array, the last two elements are the same object (array):

 cap[ cap.length - 1 ] === [ cap.length - 2 ] => true 

need to clone an array:

 cap[ cap.length ] = cap[ cap.length - 1 ].slice(); cap[ cap.length - 2 ][ 3 ] = 1; 
  • Yes, thank you very much, it works that way. - Alex