I checked the "Similar questions" but I either didn't understand the answers or they didn't seem relevant to this question.
In certain cases I can't seem to overwrite array values when I try (Loop3), and in others, the array values get overwritten when I think they shouldn't be (Loop4). I just edited the code to show more values at various points.
<script>
function manual() {
myArray = [];
td=[1,2,3];
myArray.push(td);
td=[4,5,6];
myArray.push(td);
alert(myArray[0]); // Properly reports [1,2,3]
}
function loop() {
myArray = [];
td = [];
for (i=0; i<=1; i++) {
if (i==0) td=[1,2,3];
else if (i==1) td=[4,5,6];
myArray.push(td);
}
alert(myArray[0]); // Properly reports [1,2,3]
}
function loop2() {
myArray = [];
td = [];
for (i=0; i<=1; i++) {
td[i] = 9;
}
td = [1,2,3]; // Attempt to overwrite existing values
myArray.push(td);
alert(myArray[0]); // Properly returns 1,2,3
}
function loop3() {
myArray = [];
td = [];
for (i=0; i<=1; i++) {
for (j=0; j<=2; j++) {
td[j] = 9;
}
if (i==0) td=[1,2,3];
else if (i==1) td=[4,5,6];
myArray.push(td);
}
alert(myArray[0]); // Returns 9,9,9 when I expect 1,2,3
}
function loop4() {
myArray = [];
td = [];
tb = document.getElementById('myTable');
for (i=0; row = tb.rows[i]; i++) {
for (j = 0; col = row.cells[j]; j++) {
td[j] = col.innerHTML;
}
alert("td="+td); // Properly get 1,2,3 the 1st time, 4,5,6 the 2nd time
myArray.push(td);
alert(myArray); // Expect 1,2,3 the 1st run, and that's what I get
// Expect 1,2,3 | 4,5,6 the 2nd run, but get 4,5,6 | 4,5,6
}
}
</script>
<table id=myTable>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
</table>
<button onclick=manual()>Manual</button>
<button onclick=loop()>Loop</button>
<button onclick=loop2()>Loop2</button>
<button onclick=loop3()>Loop3</button>
<button onclick=loop4()>Loop4</button>