简体   繁体   English

如何在 html 中显示 javascript 数组中的所有项目,除了最后一项外,它们之间用逗号分隔

[英]How to display all items from a javascript array in html with commas in between them except the last item

I have to use a for loop or while loop.我必须使用 for 循环或 while 循环。 How do I include the last item from the array without including the comma afterward?如何在不包含逗号的情况下包含数组中的最后一项? Below I have the code that prints all items in the array except the last one.下面我有打印数组中除最后一项之外的所有项目的代码。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="coffee.css" />
    <title>Coffee</title>
  </head>
  <body>
   
    <section class="javascript">
      <h3>Drinks of the Month</h3>
      <p id="drinks"></p>
    </section>

    <script>
      var drinks = [
        "Chai Tea",
        "Sweet Cream Cold Brew",
        "Caramel Macchiato",
        "Vanilla Latte",
      ];

      var i = 0;
      var drinksOfMonth = "";
      while (i < drinks.length - 1) {
        drinksOfMonth += drinks[i] + ", ";
        i++;
      }


      document.getElementById("drinks").innerHTML = drinksOfMonth;
    </script>
  </body>
</html>

Just use join() method of array.只需使用数组的join()方法即可。

Example例子

const foo = ['tea', 'coffee', 'soda'];

console.log(foo.join('-'));
console.log(foo.join(', ');

You can read more about Array.join() here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join您可以在此处阅读有关 Array.join() 的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

This will do it:这将做到:

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
]

drinks.join(', ')

Will output:请问output:

Chai Tea, Sweet Cream Cold Brew, Caramel Macchiato, Vanilla Latte

You can also do it like this你也可以这样做

while (i < drinks.length) { 
  if(i != drinks.length-1){
    drinksOfMonth += drinks[i] + ", "}
  else{
    drinksOfMonth += drinks[i]}
 i++ 
}

I have to use a for loop or while loop.我必须使用 for 循环或 while 循环。 How do I include the last item from the array without including the comma afterward?如何在不包含逗号的情况下包含数组中的最后一项?

Why you want to use for or while loop as you can easily achieve this requirement with Array.join() method with a single line of code.为什么要使用 for 或 while 循环,因为您可以使用Array.join()方法通过一行代码轻松实现此要求。

Demo:演示:

 var drinks = [ "Chai Tea", "Sweet Cream Cold Brew", "Caramel Macchiato", "Vanilla Latte", ]; console.log(drinks.join(', '));

Just add the last item after the while loop:只需在 while 循环之后添加最后一项:

drinksOfMonth += drinks[drinks.length-1];

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

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