may beginner problem?
i implement simple recurse code.
but, it does not work.
what is wrong?
or more simple way to do?
first block is tried recurse code,
second block is sample non-recurse code. both results are should be same.
I must use recursive code.
const total = 2;
// vvvvvvvv wrong code start
let accum = 0;
let obj = [];
const loop = (total, accum, obj) => {
for (let i = 0; i < total; i++) {
obj.push(i);
if (total > accum) {
accum++;
loop(total, accum, obj);
} else {
console.log(obj);
}
obj.pop();
}
}
loop(total, accum, obj);
// ^^^^^^^^ wrong code end
console.log('-----------------------------');
// vvvvvvvv expect result
for (let i = 0; i < total; i++) {
for (let j = 0; j < total; j++) {
console.log([i, j]);
}
}
2
Answers
You are console logging the obj but also popping from it. You need to wait until it has the length you want
This works better
Delegate the inner loop to the same function and pass the current loop state as an arguments: