How to set one value in a two dimensional javascript array -
i trying set single value in 2 dimensional array, not working.
consider following code taken many examples on subject:
// create 3x3 array -1 in every position: let = new array(3).fill(new array(3).fill(-1)) console.log(`a: ${json.stringify(a)}`) a[1][2] = 0 console.log(`a: ${json.stringify(a)}`) the output follows:
a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]] a: [[-1,-1,0],[-1,-1,0],[-1,-1,0]] as can see, instead of setting single cell, set 3 positions in array 0, i.e. sets [0][2] , [1][2] , [2][2] = 0. odd.
i tried this:
let = new array(3).fill(new array(3).fill(-1)) console.log(`a: ${json.stringify(a)}`) a[1,2] = 0 console.log(`a: ${json.stringify(a)}`) which gives stranger result:
a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]] a: [[-1,-1,-1],[-1,-1,-1],0] am going crazy, or javascript not support setting value in 2 dimensional array?
first question:
that's because fill outer array same subarray! a[0], a[1] , a[2] same array! because in js objects (including arrays) passed around using references! array.fill taking parrameter (in case reference array) , assigns every item in array. it's this:
var sub = new array(3); sub.fill(-1); var = []; a[0] = sub; a[1] = sub; a[2] = sub; a[0][1] = 0; console.log(sub); // changed too because here array.fill doing:
var = new array(10); a.fill(math.random()); console.log(a); // not 10 different random numbers, same random number assigned whole array second question:
it has nothing arrays. it's comma operator 1 used in loops (for example), group expressions 1 , returning value of last:
console.log((1, 2)); // 2 console.log((1, 5, "last")); // last console.log((1, 5, 5 * 11 + 10)); // 65 // parens used distinguish comma operator parameter separator so a[1, 2] same a[2] because value of 1, 2 2!
Comments
Post a Comment