循环遍历数组中的对象,打印属性

时间:2018-03-21 10:34:02

标签: javascript html

我遇到这样的情况:



var orders = [ 
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];

const bill = document.querySelector("#ordersListed");

for(var x in orders) {
  bill.innerHTML += orders[x].order;
}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="ordersListed"></div>
</body>
</html>
&#13;
&#13;
&#13;

每次单击按钮时,项目都会添加到数组中 我一直在尝试遍历数组以在HTML元素中打印每个订单

应该在div中显示为:

  

描述第一个订单的字符串
  描述第二顺序的字符串

我的结果:

  

第一顺序
  第一顺序
  第二顺序

3 个答案:

答案 0 :(得分:2)

只需在数组&#39; s <br>的每次迭代中向innerHTML添加forEach()即可:

&#13;
&#13;
var orders = [ 
  {ID: "sampleID1", order: "string describing the first order"},
  {ID: "sampleID2", order: "string describing the second order"}
];

const bill = document.querySelector("#ordersListed");

orders.forEach(o => bill.innerHTML += o.order + '<br>');
&#13;
<div id="ordersListed"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

for...in用于迭代Object属性,而不是Array。使用for...of

var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]

for (order of orders) {
  let para = document.createElement('p')
  para.textContent = order.order
  ordersListed.appendChild(para)
}
#ordersListed {
  background: #f8f8f8;
  border: 4px dashed #ddd;
  padding: 5px 15px;
}
<div id="ordersListed"></div>

注意:我更喜欢创建真正的DOM节点,因此我可以轻松添加属性并附加事件处理程序。在第二个示例中,我显示了添加标题并在点击时提醒订单ID:

var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]

for (order of orders) {
  let para = document.createElement('p')
  para.textContent = order.order
  para.title = order.ID
  para.addEventListener('click', function() { alert(this.title) })
  ordersListed.appendChild(para)
}
#ordersListed {
  background: #f8f8f8;
  border: 4px dashed #ddd;
  padding: 5px 15px;
}

#ordersListed p {
  cursor: pointer;
}
<div id="ordersListed"></div>

答案 2 :(得分:0)

怎么样:

var orders = [ 
  {ID: "sampleID1", order: "string describing the first order"},
  {ID: "sampleID2", order: "string describing the second order"}
];

for (var i = 0; i < orders.length; i++ ) {
  orderListContainer.textContent += orders[i]['order'];
}

据我所知,你将数组元素而不是正确的属性附加到数组元素。