通过数组显示输入

时间:2017-04-27 07:35:17

标签: javascript arrays

我有三个输入框。一旦用户将数据添加到三个输入框中,他们就会单击一个按钮,将该数据添加到数组中。我希望多个人能够将数据添加到输入框中,然后单击按钮将该数据添加到数组中。页面上还有另一个按钮,允许用户查看数组中的所有数据,并告诉他们数组中有多少个值。这是我到目前为止所做的,虽然我确定大部分都是不正确的,因为我刚开始学习javascript。有人可以帮我一把吗?非常感激。

var customerarray = [];

function displaydata() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('custID').value;
var AmountDue = document.getElementById('Amount').value;
var innerTemphtml = '';
for(var i=0;i<customerarray.length;i--) {
  innerTemphtml + = customerarray[i].customerName+ " " + customerarray[i].customerID+ " " + customerarray[i].AmountDue;

     }
  document.getElementById('output').innerHTML=innerTemphtml ;
 }

function addtoarray() {
customerarray.push({customerName:document.getElementById('custName').value, 
customerID: document.getElementById('custID').value, 
AmountDue: docment.getElementById('Amount').value});
}
<body>
<span>Customer Name: </span>
<input type="text" id=custName></input><br><br>
<span>Customer ID: </span>
<input type="text" id=CustID></input><br><br>
<span>Amount: </span>
<input type="text" id=Amount></input> <br><br>
<button onclick="displaydata()" class="button" type = "button">add to array</button>
<button onclick="addtoarray()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>

1 个答案:

答案 0 :(得分:1)

替换此

var i = customerarray.length
while (i--) {
  document.getElementById('output').innerHTML = customerarray[i].custName + " " + customerarray[i].custID + " " + customerarray[i].Amount;

}

有了这个

var innerTemphtml = '';
for(var i=0;i<customerarray.length;i--) {
  innerTemphtml + = customerarray[i].customerName+ " " + customerarray[i].customerID+ " " + customerarray[i].AmountDue;

     }
  document.getElementById('output').innerHTML=innerTemphtml ;
 }

替换后的最终守则

var customerarray = [];

function displaydata() {
  var innerTemphtml = ' ';
  for (var i = 0; i < customerarray.length; i++) {

    innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
  }
  document.getElementById('output').innerHTML = innerTemphtml;

}

function addtoarray() {
  customerarray.push({
    customerName: document.getElementById('custName').value,
    customerID: document.getElementById('CustID').value,
    AmountDue: document.getElementById('Amount').value
  });
}

<强>观察

  • while
  • 的无限循环
  • 用于构造对象和使用的属性是不同的,这将导致undefined

Try this working Demo