如何使用JavaScript将两个值添加到数组中

9avjhtql  于 2022-12-28  发布在  Java
关注(0)|答案(4)|浏览(273)

我想把文本框中的值加到数组中,我试过了,但是只能加一个值,为什么?如果可以的话,我是怎么做到的?
这是我试过的密码

<script type="text/javascript">
  var x = 0;
  var y = 0;
  var array = Array();

  function addintoarray() {
    array[x] = document.getElementById("cuna").value; //create the array for to add customer name
    array[y] = document.getElementById("cuad").value; //create the array to add customer address
    alert("Customername: " + array[x] + "Added" + "Customeraddress: " + array[y] + "Added"); //display msg
    x++; //count increment to add another one
    y++;
    document.getElementById("cuna").value = "";
    document.getElementById("cuad").value = "";
  }

</script>

<form method="post">
  <table border="1">
    <tr>
      <td>CustomerName</td>
      <td><input type="text" id="cuna" /></td>
    </tr>
    <tr>
      <td>CustomerAddress</td>
      <td><input type="text" id="cuda" /></td>
    </tr>
    <tr>
      <td><input type="submit" value="Add" onclick="addintoarray();" />
      </td>
      <td><input type="Submit" value="Display" onclick="displayintoarray" /></td>
    </tr>
  </table>
</form>
x8diyxa7

x8diyxa71#

您将xy都初始化为0,因此每次执行array[x] =array[x] =时,都将目标元素定位在索引0处。如果您想添加项,可以使用JavaScript's array.push()方法。

使用JavaScript对象来存储值因为我注意到您希望不断地向数组中添加内容,所以您应该考虑使用对象来对数组中的数据进行分组。

function addintoarray() {
    let name = document.getElementById("cuna").value; 
    let address = document.getElementById("cuad").value;

    myArray.push({'customerName':name,'customerAddress':address})

    alert("Customername: " + name + "Added. " + "Customeraddress: " + address + "Added");

}`
sulc1iza

sulc1iza2#

你应该做的是改变x和y的值。

var x = 0;
var y = 1;
var array = Array();

那这个就行了。

array[x] = document.getElementById("cuna").value; 
array[y] = document.getElementById("cuad").value;

但是我认为你不需要这样做,你可以使用数组push方法。

array.push(document.getElementById("cuna").value)
 array.push(document.getElementById("cuad").value)
2izufjch

2izufjch3#

我想你希望结果是这样的:
[[库纳1,库纳1][库纳2,库纳2]]
在这种情况下,应执行以下操作:

let arrayToPush = [document.getElementById("cuna").value,document.getElementById("cuad").value]

(btw小心你的HTML中有一个打字错误:用"cuda"代替"cuad")
然后

array.push(arrayToPush)

x = 0和y = 1的解决方案将不起作用,因为在第二轮x将是1和y将是2,因此array [x]将覆盖以前的值。然而,他们说你应该避免使用索引,而只是推到数组是正确的。

ezykj2lf

ezykj2lf4#

你用x,y作为索引,用相同的值来替换,你先赋值array[x],然后赋值array[y],这意味着在初始情况下

array[0]=document.getElementById("cuna").value;
array[0]=document.getElementById("cuad").value;

您可以使用两个不同的初始值,如x=0,y=1,并且仍然使用增量值x += 2; y += 2;
相反,您可以使用数组原型来推送值

array.push(document.getElementById("cuna").value);
array.push(document.getElementById("cuad").value);

相关问题