The goal is to create a dynamic 'sum' row in a 2d javascript array. Here's the starting point:
var m = [[1,2,3], [4,5,6]];
We can add a third row thus:
Object.defineProperty(m, 2, { get: () => m[0].map((e, i)=> e + m[1][i]) })
So now our array is
[[1,2,3], [4,5,6], [5,7,9]]
It works! Setting m[0][0]=10 and we get
[[10,2,3], [4,5,6], [14,7,9]]
which is exactly what I want. m.length = 3 as expected, so the sum row is being treated as part of the array. JSON.stringify works as expected too. (I was a bit surprised it worked tbh).
My question is - is there a way of generating parts of a 2d array dependent on other parts without resorting to defineProperty? Is this something to avoid?
(Note - in my original question I had done the above, then changed m[2] to something else. The 'property' won over the array member, which lead to some confusion. This in itself may be a reason not to use the above method. Apolgies.)
m[2]=m[2]()somewhere before having:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 5, 7, 9 ] ]m[2]=m[2]()as Marcs says. It actually throws an error if you try to callm[2]=m[2](). Getters don't need to be called before they work