Z
Z
Zakharov Alexander2015-09-23 15:55:39
JavaScript
Zakharov Alexander, 2015-09-23 15:55:39

Is it possible to bypass a nested array with one variable (from the category of self-entertainment)?

The question is from the category of self-entertainment / masochism and idiocy. Please don't take it seriously.
For example, there is such an array:

var a = 
[
    [
        [1, 2, 3], 
        [4, 5, 6]
    ],
    [
        [7, 8, 9], 
        [10, 11]
    ]
]

You need to bypass it with a for () loop using one variable. No recursions . Where the legs grow from: sometimes in the work there are arrays with a nesting level of 5, while each level is sufficiently isolated and does not affect the other. It's a little "annoying" to introduce new variables i,j,k,l,m. I want everyone to be called the same variable "i".
It doesn't work at all , but I hope you get the idea:
function fff(){
    debugger;
    var a = [,];
    for(var i=0; i<=a.length-1; i++){
        var a_i = a[i];
        for(var i=0; i<=a_i.length-1; i++){
           var a_i_i=a_i[i];
           for(var i=0; i<=a_i_i.length-1; i++){
               var a_i_i_i = a_i_i[i];
               console.log( a_i_i_i );
           }
        }
    }
}

Here is a working version:
function fff(){
    debugger;
    var a = [,];
    for(var i=0; i<=a.length-1; i++){
        var a_i = a[i];
        (function(){for(var i=0; i<=a_i.length-1; i++){
           var a_i_i=a_i[i];
           (function(){for(var i=0; i<=a_i_i.length-1; i++){
               var a_i_i_i = a_i_i[i];
               console.log( a_i_i_i );
           }})()
        }})()
    }
}

There are no recursions, but there are anonymous functions. Quite suitable.
At the output: 1,2,3,4,5,6,7,8,9,10,11 - in general, there is a result. You can try it in Chrome Debugger:
0b7efdc036204b0cbdbe1fd643d36fe6.png
Any other options?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MhMadHamster, 2015-09-23
@MhMadHamster

your version will break if you increase the nesting

function foo() {
  var arr = [,]];
  arr = arr.join(',').split(',');
  for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  };
};

A
Aves, 2015-09-23
@Aves

Why no recursions? The nesting of scopes is the same, only the notation is shorter.

function iterate(e){
    if (Array.isArray(e)) e.forEach(iterate);
    else console.log(e);
}
iterate(a);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question