我正在创建一个对象,将该对象的属性放入数组中,然后将该数组映射到HTML输出,最后却出现一行逗号?这些逗号从哪里来?
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>')
以下是HTML的小提琴: https://jsfiddle.net/ruzel/qyrczkup/3/
答案 0 :(得分:5)
map
返回另一个数组,当您将其传递给innerHTML
时,它将成为它的字符串版本。
只需尝试:console.log(results.map(r => '<p>' + r + '</p>').toString())
返回:<p>Square</p>,<p>4</p>,<p>6</p>,<p>36</p>
要解决此问题,只需将该数组正确转换为字符串,然后再将其设置为HTML:
resultsDiv.innerHTML = results.map(r => '<p>' + r + '</p>').join('')
答案 1 :(得分:1)
您还可以使用reduce
和template string
来解决此问题,因为map返回一个数组,而InnerHTML在该数组上执行了toString
:
resultsDiv.innerHTML = results.reduce((r,c) => r.concat(`<p>${c}</p>`), '')