JavaScript 递归字符串拼接

3
我正在尝试将嵌套数组递归地转换为有序HTML列表。我的测试数组如下:[['A','B','C'],['D',['E','F','G']]],结果应该是:
    1. A
    2. B
    3. C
    1. D
      1. E
      2. F
      3. G
目前它返回的是:
    1. A
    2. B
    3. C
    1. D
    2. E,F,G
当我将其打印出来时,递归是成功的,但被前一步覆盖了。我觉得这与在函数顶部声明字符串有关,但我不确定如何以其他方式处理它。 JSFIDDLE: https://jsfiddle.net/nzyjoawc/2/

1
展示你的代码? - Ouroborus
我在顶部添加了一个JSFiddle,但我也可以在这里发布它。 - metalkat
也许只是让它更加突出,似乎人们错过了它。 - Ouroborus
1个回答

3

使用递归完成,并使用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))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接