javascript递归字符串concatenation
问题描述:
我想递归地将一个嵌套数组转换为一个有序的HTML列表。 我的测试阵列看起来像:[['A','B','C'],['D',['E','F','G']]]
而结果应该看起来像:javascript递归字符串concatenation
-
- 甲
- 乙
- Ç
-
- d
-
- Ë
- ˚F
- ģ
但是它是目前返回:
-
- 甲
- 乙
- Ç
-
- d
- 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))
显示你的代码? – Ouroborus
我在顶部添加了一个JSFiddle,但我也可以在这里发布它。 – srukali
也许只是让它脱颖而出,似乎人们错过了它。 – Ouroborus