繁体   English   中英

我不知道如何解决这个问题,你能帮我吗?

[英]I have no idea how to solve this problem, can you help me?

我不知道如何解决这个问题,你能帮我吗?

如何转换这个:

const array = [["1", ["2", ["3"]]]];

在此(并考虑数组可以是无限循环):

<p>
    1
    <p>
        2<p>3</p>
    </p>
</p>;

不是这个:

array.forEach(el => {
    el.forEach(el => {
        el.forEach(el =>{

        })
    })
})

您需要使用递归。 其他答案似乎使这变得不必要地复杂。 你只需要这样:

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

如果这解决了您的问题,那么您可以将其标记为正确。

注意:你实际上不能嵌套<p>元素,所以这是<divs>

(即使你有一个奇怪的数组,如["1", "2", ["3", [["5", "6"]]]]也可以使用)
使用递归 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; }

您可以检查该值,如果数组 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);

谢谢大家:这让我明白了如何实现它是下面的例子:

 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>

这是不切实际的。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM