【问题标题】:javascript recursive string concatentationjavascript递归字符串连接
【发布时间】:2016-11-21 03:37:09
【问题描述】:

我正在尝试递归地将嵌套数组转换为有序的 HTML 列表。 我的测试数组看起来像:[['A','B','C'],['D',['E','F','G']]] 结果应该是这样的:

    1. 一个
    2. B
    3. C
    1. D
      1. E
      2. F
      3. G

但它目前正在返回:

    1. 一个
    2. B
    3. C
    1. D
    2. E,F,G

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

JSFIDDLEhttps://jsfiddle.net/nzyjoawc/2/

【问题讨论】:

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

标签: javascript html recursion


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多