繁体   English   中英

使用.map() 方法将数组项渲染到自己单独的div中,但逗号仍在显示?

[英]Using .map() method to render array items into their own separate divs, but comma is still displaying?

我已经搜索和搜索,但我只找到了解决方案 to.join() 将项目放入单个字符串中..

const createCard = () => {
    const pokemonTypes = ['grass', 'fire', 'water'];
      return (
        `<div>
          ${pokemonTypes.map(type => `<div>${type}</div>`)}
        </div>`
      )
}

document.body.insertAdjacentHTML("beforeend", createCard());

在某些情况下,我使用的是 API,但我简化了代码,使其快速且易于阅读。

我正在尝试将每个字符串显示到自己的 div 中,以便我可以单独设置每个 div 的样式......就像颜色编码的按钮:绿色代表草,蓝色代表水,红色代表火等。

当我运行代码时,字符串成功显示在自己的 div 中,但是逗号仍然存在。 我希望它们只显示在每个旁边,而不用逗号分隔它们。

.map()方法返回一个数组。 在模板文字`${}`中,js 会将此数组转换为字符串。 默认情况下,它通过用逗号连接元素来做到这一点。 您可以自己将数组加入字符串,无需逗号:

${pokemonTypes.map(type => `<div>${type}</div>`).join('')}

Array.map返回一个数组作为 output。 将此数组设置为 html 内容与将数组转换为字符串相同。

例子

 const numArray = [1, 2, 3]; console.log(numArray.toString());

将数组转换为字符串将始终包含中间的逗号。

你的表情和下面一样

 document.body.insertAdjacentHTML("beforeend", [1, 2, 3]);

你要做的是你必须用空字符串加入这个数组,并将这个单个字符串设置为 html 常量,如下所示。

使用.join('')加入不带逗号的数组

 const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ( `<div> ${pokemonTypes.map(type => `<div>${type}</div>`).join('')} </div>` ); } document.body.insertAdjacentHTML("beforeend", createCard());

您可以将.join('')用于字符串具体和用于样式的相同类型。

 const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ( `<div> ${pokemonTypes.map(type => `<div class="${type}">${type}</div>`).join('')} </div>` ); } document.body.insertAdjacentHTML("beforeend", createCard());
 .grass { color: green }.fire { color: red }.water { color: blue }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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