1

I'm creating an object, putting the attributes of that object into an array and then mapping the array to HTML output and I end up with line after line of commas? Where are these commas coming from?

let results = []

class Polygon {
  constructor() {
    this.name = "Hexagon"
    this.edges = 6
    this.size = 1
  }
  setName(value) {
    this.name = value
  }
  setEdges(value) {
    this.edges = value
  }
  setSize(value) {
    this.size = value
  }
  getArea() {
    return this.size * this.size
  }
}

let shape = new Polygon()
shape.setName("Square")
shape.setEdges(4)
shape.setSize(6)

results.push(shape.name)
results.push(shape.edges)
results.push(shape.size)
results.push(shape.getArea())

console.log(results)

resultsDiv = document.querySelector('#results')
resultsDiv.innerHTML = results.map(r => '<p>' + r + '</p>')

Here's the fiddle with the HTML: https://jsfiddle.net/ruzel/qyrczkup/3/

2 Answers 2

5

map returns another array and when you pass it to innerHTML, it becomes a string version of it.

Just try it: console.log(results.map(r => '<p>' + r + '</p>').toString()) returns: <p>Square</p>,<p>4</p>,<p>6</p>,<p>36</p>

To solve this, just transform that array to a string properly before setting it as HTML:

resultsDiv.innerHTML = results.map(r => '<p>' + r + '</p>').join('')
Sign up to request clarification or add additional context in comments.

Comments

1

You can also resolve this with reduce and template string since map returns an array and InnerHTML does toString on the array:

resultsDiv.innerHTML = results.reduce((r,c) => r.concat(`<p>${c}</p>`), '')

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.