I have to use a for loop or while loop. 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.
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
This will do it:
var drinks = [
"Chai Tea",
"Sweet Cream Cold Brew",
"Caramel Macchiato",
"Vanilla Latte",
]
drinks.join(', ')
Will 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. 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.
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:
drinksOfMonth += drinks[drinks.length-1];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.