我正在尝试以递归方式将嵌套数组转换为有序的 HTML 列表。
我的测试数组如下所示:[['A','B','C'],['D',['E','F','G']]]
结果应该是这样的:
- A
- B
- C
- D
- E
- F
- G
但它目前正在返回:
- A
- B
- C
- 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))
关于javascript递归字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40712377/