[英]I have no idea how to solve this problem, can you help me?
I have no idea how to solve this problem, can you help me?我不知道如何解决这个问题,你能帮我吗?
How to transform this:如何转换这个:
const array = [["1", ["2", ["3"]]]];
In this (and consider that the array can be an infinite loop):在此(并考虑数组可以是无限循环):
<p>
1
<p>
2<p>3</p>
</p>
</p>;
Not this:不是这个:
array.forEach(el => {
el.forEach(el => {
el.forEach(el =>{
})
})
})
You need to use recursion.您需要使用递归。 Other answers seem to make this unnecessarily complicated.
其他答案似乎使这变得不必要地复杂。 All you need is this:
你只需要这样:
function makeP(arr) {
if (arr.length == 1) {
return "<p>" + arr[0] + "</p>";
}
return "<p>" + arr[0] + makeP(arr[1]) + "</p>";
}
// Remove the unneeded extra nested array
const array = ["1", ["2", ["3"]]];
console.log(makeP(array));
// output: "<p>1<p>2<p>3</p></p></p>"
If this solved your problem, then you can mark it as correct.如果这解决了您的问题,那么您可以将其标记为正确。
NOTE: You can't actually nest <p>
elements, so this is with <divs>
注意:你实际上不能嵌套
<p>
元素,所以这是<divs>
(This works even if you have a weird array like ["1", "2", ["3", [["5", "6"]]]]
) (即使你有一个奇怪的数组,如
["1", "2", ["3", [["5", "6"]]]]
也可以使用)
Use a recursive function:使用递归 function:
const array = [["1", ["2", ["3"]]]]; document.body.innerHTML += createDivs(array) function createDivs (array) { let result = "<div>" array.forEach(elem=>{ if (typeof elem === "string") { result += elem } else if (typeof elem === "object") { // Arrays are objects, too result += createDivs(elem) } }) result += "</div>" return result }
div { border: 1px solid black; padding: 10px; }
You could check the value and if an array map the values with p
tag otherwise take only the value.您可以检查该值,如果数组 map 带有
p
标签的值,否则只取该值。
const format = value => Array.isArray(value)?`<p>${value.map(format).join('')}</p>`: value, data = ["1", ["2", ["3"]]], result = format(data); console.log(result);
Thank you all: This allowed me to understand how to achieve it is example below:谢谢大家:这让我明白了如何实现它是下面的例子:
const demo = [ { content: "ligne 1", items: [], }, { content: "ligne 2", items: [ { content: "ligne 2.1", items: [ { content: "ligne 2.1.1", items: [], }, { content: "ligne 2.1.2", items: [], }, ], }, ], }, { content: "ligne 3", items: [], }, ]; const type = "ol" const createList = (items, type) => { let li = ""; const loop = (items, type) => { items.forEach((el) => { if (el.items.length == 0) { li += `<li>${el.content}</li>`; return; } li += `<li>${el.content}</li><${type}>`; loop(el.items, type); li += `</${type}>`; }); }; loop(items, type); return li; }; const result = createList(demo, type) console.log(`<${type}>`,result,`</${type}>`) document.getElementById('container').innerHTML = result
<ol id='container'></ol>
This is not practical.这是不切实际的。
const array = [["1", ["2", ["3"]]]]; const result = JSON.stringify(array).replace(/"|,|^.|.$/g, "").replace(/\[/g, "<p>").replace(/]/g, "</p>") console["log"](result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.