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

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

我找了又找,但我只找到了将项目 .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()方法returns一个数组。在模板字面量 `${}` 中,js 会将这个数组转换为字符串。默认情况下,它通过用逗号连接元素来做到这一点。您可以自己将数组连接到字符串而不用逗号:

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

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

例子

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

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

你的表情和下面的一样

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

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

使用.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
}