+ 2

There is erro

Why this code works so strange: var Field = new Array(10).fill(new Array(10)); var N=10; for(let i=0; i<N; i++){ for(let j=0; j<N; j++){ let tmpStr=i+"."+j; Field[i][j]={cellId: tmpStr, isVisited: false, visible: 0}; } } for(let i=0; i<N; i++) { for(let j=0; j<N; j++) { console.log(Field[i][j].cellId); } } CellId for all rows has 9.x format.

10th Dec 2018, 5:48 AM
Igor Kostrikin
Igor Kostrikin - avatar
6 Antworten
+ 4
Igor I apologize for the delayed response to follow up question. There is nothing wrong with "var Field = new Array(10).fill(new Array(10));" It just that the outcome from that line of code hinders what you are trying to accomplish. "When fill() gets passed an object, it will copy the reference and fill the array with references to that object." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill So all ten arrays are referencing the same memory location holding one array. Hence the reason for the 9.x. I created a demo based on your snippet of code. Think it may make more sense than my explanation https://code.sololearn.com/WXHnFBV0Jq7a/#css
13th Dec 2018, 4:26 AM
ODLNT
ODLNT - avatar
+ 3
var field = []; var N=10; for(let i=0; i<N; i++){ field.push([]); for(let j=0; j<N; j++){ let tmpStr=i+"."+j; field[i].push({cellId: tmpStr, isVisited: false, visible: 0}); } }
10th Dec 2018, 7:07 AM
ODLNT
ODLNT - avatar
+ 1
Can you give the code? Lol im lazy to copy it :))
10th Dec 2018, 5:53 AM
ShortCode
+ 1
Thank you.
10th Dec 2018, 7:19 AM
Igor Kostrikin
Igor Kostrikin - avatar
+ 1
What's wrong with var Field = new Array(10).fill(new Array(10)); ?
10th Dec 2018, 7:29 AM
Igor Kostrikin
Igor Kostrikin - avatar
10th Dec 2018, 5:56 AM
Igor Kostrikin
Igor Kostrikin - avatar