2016-11-21 103 views
3

我想遞歸地將一個嵌套數組轉換爲一個有序的HTML列表。 我的測試陣列看起來像:[['A','B','C'],['D',['E','F','G']]] 而結果應該看起來像:javascript遞歸字符串concatenation

    1. Ç
    1. d
      1. Ë
      2. ˚F
      3. ģ

但是它是目前返回:

    1. Ç
    1. d
    2. E,F,G

當我打印出來,遞歸是成功的,但被前面的步驟覆蓋。我覺得它與在函數頂部聲明字符串有關,但我不知道如何處理它。

的jsfiddlehttps://jsfiddle.net/nzyjoawc/2/

+1

顯示你的代碼? – Ouroborus

+0

我在頂部添加了一個JSFiddle,但我也可以在這裏發佈它。 – srukali

+0

也許只是讓它脫穎而出,似乎人們錯過了它。 – Ouroborus

回答

3

recursion這樣做,可以使用Array#forEach方法用於遍歷數組。

var a = [ 
 
    ['A', 'B', 'C'], 
 
    ['D', ['E', 'F', 'G']] 
 
]; 
 

 
function gen(arr) { 
 
    // create `ol` eleemnt 
 
    var ol = document.createElement('ol'); 
 
    // iterate over the array eleemnt 
 
    arr.forEach(function(v) { 
 
    // create list item `li` 
 
    var li = document.createElement('li'); 
 
    // if array element is an array then do recursion 
 
    // and append the returnd value 
 
    if (Array.isArray(v)) 
 
     li.appendChild(gen(v)); 
 
    // else set the content as array value 
 
    else 
 
     li.innerHTML = v; 
 
    // append the list item to the list 
 
    ol.appendChild(li); 
 
    }); 
 
    // resturn the genarated list 
 
    return ol; 
 
} 
 

 
document.body.appendChild(gen(a))