javascript递归字符串连接

标签 javascript html recursion

我正在尝试以递归方式将嵌套数组转换为有序的 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/

最佳答案

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

关于javascript递归字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40712377/

相关文章:

Javascript:类型错误:回调不是函数

javascript - 如何优雅地停止为 Nodejs 编写的 Azure WebJob

javascript - 在按下选项卡时它不会移动到下一个选项卡

html - Web 浏览器引擎和特殊字符渲染

recursion - 使用 CPS 删除 Scheme 中的子序列函数(深度递归)

通过递归检查尾部来迭代列表的性能

javascript - 在页面上创建多个元素与更改一个元素

javascript - NodeJS 转义反斜杠

html - 即使减小浏览器的宽度,如何将页脚保持在屏幕底部?

algorithm - 不使用数组递归创建所有子集