I have 2 dim array, which looks like this:
var a = [[1,2,3],[4,5,6],[7,8,9]];
I want to write an iterator which will return one value a time when it's called.
iterator(); //returns 1
iterator(); //returns 2
iterator(); //returns 3
I tried such approach:
function iterator() {
var a = [[1,2,3],[4,5,6],[7,8,9]];
var i, j;
return function() {
for (var i = 0; i < a.length; i++) {
var b = a[i];
for (var j = 0; j < b.length; j++) {
return a[i][j];
}
}
}
};
var a = iterator();
a(); //1
a(); //1
a(); //1
It always returns me first element.
I can try this one:
function iterator() {
var a = [[1,2,3],[4,5,6],[7,8,9]];
var i = 0, j = 0;
return function() {
for (; i < a.length; i++) {
var b = a[i];
for (; j < b.length; j++) {
return a[i][j];
}
}
}
};
Also not works.
But if I try this one:
function test() {
var a = [1,2,3,4,5], i = 0;
return function() {
while (i < a.length) {
return a[i++];
}
}
}
var a = test();
a(); //1
a(); //2
a(); //3
It works fine.
What is the difference here? How to make for loop work?
One other visible problem for me is bounds. How should I stop when I reach array bounds?
Instead of using an inner for-loop for the second dimension you can use a simple if
to test the bounds of j
function iterator() {
var a = [[1,2,3],[4,5,6],[7,8,9]];
var i = 0, j = 0;
return function() {
for (; i < a.length; i++) {
var b = a[i];
if (j < b.length){
return a[i][j++];
}
j = 0;
}
return undefined; // reached when there is no value left
}
};