javascript递归字符串连接

时间:2016-11-21 03:37:09

标签: javascript html recursion

我试图以递归方式将嵌套数组转换为有序的HTML列表。 我的测试数组看起来像:[['A','B','C'],['D',['E','F','G']]] 结果应该如下:

    1. A
    2. C
    1. d
      1. 电子
      2. ˚F
  1. 但目前正在回归:

      1. A
      2. C
      1. d
      2. E,F,G

    当我打印出来时,递归成功,但被上一步覆盖。我觉得它与在函数顶部声明字符串有关,但我不确定如何处理它。

    JSFIDDLE https://jsfiddle.net/nzyjoawc/2/

1 个答案:

答案 0 :(得分: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))




相关问题