0

Im printing out items in an array in an HTML list:

"use strict";

var giftArray = ["kettle", "iron", "bed", "tv", "lamp"];
var gifts = function() {
  var values= [];
  for (var i = 0; i < giftArray.length; i++) {
    values.push("<li>" + giftArray[i] + "</li>");
  }
  document.write("<ul>" + values + "</ul>");
}

gifts();

Its working except that it includes a comma after each result. Why is this happening and how can I stop it?

2 Answers 2

1

Use join() with an empty string as delimiter

document.write("<ul>" + values.join('') + "</ul>");

The default when writng an array into dom is to convert it to string using Array.prototype.toString() which includes the comma delimter

Sign up to request clarification or add additional context in comments.

Comments

0

If you concatenate an array with a string you get the default array .toString() representation, which is all the elements joined with commas.

Use the .join() method to join all of the elements of the array with the separator of your choice, e.g., with an empty string:

var giftArray = ["kettle", "iron", "bed", "tv", "lamp"];
var gifts = function() {
  var values= [];
  for (var i = 0; i < giftArray.length; i++) {
    values.push("<li>" + giftArray[i] + "</li>");
  }
  document.write("<ul>" + values.join("") + "</ul>");
}

gifts();

Or you can use .join() instead of your loop, to join your original giftArray with appropriate HTML tags:

var giftArray = ["kettle", "iron", "bed", "tv", "lamp"];
var gifts = function() {
  document.write("<ul><li>" + giftArray.join("</li><li>") + "</li></ul>");
}

gifts();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.