2016-10-15 5 views

Antwort

1

versuchen, diese

const inputs = [1,3,[6],7,[8]] 
 

 
/** loop array */ 
 
for (const input of inputs) { 
 
    if (Array.isArray(input)) { 
 
    /** input is array, loop nested array */ 
 
    for (const nestedInput of input) { 
 
     /** print item of nested array */ 
 
     console.log(nestedInput) 
 
    } 
 
    } 
 
    else { 
 
    /** input is number, print it */ 
 
    console.log(input) 
 
    } 
 
}

beachten Sie, dass: es gibt so viele Möglichkeiten, um Schleife sind, for..of, forEach, für, während, usw.

2

Sie könnten einen rekursiven Ansatz für die Iteration mit Array#forEach verwenden.

var array = [1, 3, [6], 7, [8]]; 
 

 
array.forEach(function iter(a) { 
 
    if (Array.isArray(a)) { 
 
     a.forEach(iter); 
 
     return; 
 
    } 
 
    console.log(a); 
 
});