While creating a matrix in Javascript (array of arrays) I used two different ways -
1. Using Array.fill
// Create a matrix using .fill
var aMatrix = new Array(5).fill(new Array(5));
aMatrix[0][0] = 'X';
// 'X' gets copied to all the 0th elements of each row
console.log(aMatrix);
function visualize(aArray, title) {
// Utility method to visualize value
var oTable = document.createElement("table");
var oTh = document.createElement("th");
oTh.setAttribute('colspan', 5);
oTh.innerHTML = "<td>" + title + "</td>";
oTable.appendChild(oTh);
for (var iIndex = 0; iIndex < 5; iIndex++) {
var oRow = document.createElement("tr");
for (var jIndex = 0; jIndex < 5; jIndex++) {
var oColumn = document.createElement("td");
oColumn.innerHTML = aArray[iIndex][jIndex] ? aArray[iIndex][jIndex] : '';
oRow.appendChild(oColumn);
}
oTable.appendChild(oRow);
}
document.body.appendChild(oTable);
}
visualize(aMatrix, "Matrix created Using Fill");
body{
font-family: Helvetica;
}
table {
border: 1px solid black;
margin: 20px;
}
table th {
text-align: center;
}
table td{
border: 1px solid #efefef;
width: 40px;
height: 40px;
background: #3399FF;
text-align: center;
}
table td:empty{
background: #efefef;
}
<center><h3>
While calling aMatrix[0]0] = 'X';
</h3>
</center>
2. Using good old loop
// Create a matrix using loop
var bMatrix = new Array(5);
for (var iRow = 0; iRow < 5; iRow++) {
bMatrix[iRow] = new Array(5);
}
bMatrix[0][0] = 'X';
function visualize(aArray, title) {
// Utility method to visualize value
var oTable = document.createElement("table");
var oTh = document.createElement("th");
oTh.setAttribute('colspan', 5);
oTh.innerHTML = "<td>" + title + "</td>";
oTable.appendChild(oTh);
for (var iIndex = 0; iIndex < 5; iIndex++) {
var oRow = document.createElement("tr");
for (var jIndex = 0; jIndex < 5; jIndex++) {
var oColumn = document.createElement("td");
oColumn.innerHTML = aArray[iIndex][jIndex] ? aArray[iIndex][jIndex] : '';
oRow.appendChild(oColumn);
}
oTable.appendChild(oRow);
}
document.body.appendChild(oTable);
}
visualize(bMatrix, "Matrix created Using Loop");
body{
font-family: Helvetica;
}
table {
border: 1px solid black;
margin: 20px;
}
table th {
text-align: center;
}
table td{
border: 1px solid #efefef;
width: 40px;
height: 40px;
background: #3399FF;
text-align: center;
}
table td:empty{
background: #efefef;
}
<center><h3>
While calling aMatrix[0]0] = 'X';
</h3>
</center>
On calling matrix[0][0] = 'X' , my expectation was that only 1st element of 1st row would be set to 'X'.
However, in first case, assigning a value to aMatrix[0][0] ends up assigning it to the entire 1st column of all rows.
Why does this happen ?