2016-10-15 39 views

回答

1

試試這個

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) 
 
    } 
 
}

需要注意的是:有這麼多的循環方式,for..of,的forEach,對,同時,等等。

2

您可以使用遞歸方法與Array#forEach進行迭代。

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

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