I'm just starting in javascript, and for my debut I simply wanted to fill each cases in tab with 0. So I tried an approach that is familiar to me since I already had the opportunity to write code in C
let tab = [[], [], [], []]
function put_zero()
{
for (var i = 0; i < 16; i++)
{
var x = i / 4;
var y = i % 4;
tab[x][y] = 0;
}
}
function print_tab()
{
for (var i = 0; i < 4; i++)
if (tab[i].length <= 0)
return;
for (var i = 0; i < 16; i++)
{
var x = i / 4;
var y = i % 4;
if (x != 0 && y % 4 == 0)
document.write("<br>");
document.write(tab[x][y]);
}
document.write("<br>");
}
function tst(){
put_zero();
print_tab();
}
function myFunction() {
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
btn.onclick = tst();
document.body.appendChild(btn);
}
But this way of doing with the i % 4 and i / 4 don't work in javascript but functional in C because before posting the question I checked anyway, so is there a reason for that? Because if I use a double loop it's ok
let tab = [[], [], [], []]
function put_zero()
{
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
tab[i][j] = 0;
}
function print_tab()
{
for (var i = 0; i < 4; i++)
if (tab[i].length <= 0)
return;
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
{
if (i != 0 && j % 4 == 0)
document.write("<br>");
document.write(tab[i][j]);
}
document.write("<br>");
}
function tst(){
put_zero();
print_tab();
}
function myFunction() {
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
btn.onclick = tst();
document.body.appendChild(btn);
}