[英]How to add two values into the array using JavaScript
好吧,我想将文本框中的值添加到数组中,我试过但是它只能添加一个值,为什么?如果可能的话,我怎么能实现呢? 在我尝试过的代码下面,
<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 custumer name
array[y] = document.getElementById("cuad").value; //create the array to add custemer address
alert("Custmername: " + array[x] + "Added" + "Custmeraddress: " + array[y] + "Added"); //display msg
x++; //count increament to add another one
y++;
document.getElementById("cuna").value = "";
document.getElementById("cuad").value = "";
}
</script>
表
<form method="post">
<table border="1">
<tr>
<td>CustmerName</td>
<td><input type="text" id="cuna" /></td>
</tr>
<tr>
<td>CustmerAddress</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>
您将x
和y
都初始化为0
因此每次执行array[x] =
或array[x] =
时都将索引为0
的元素作为目标。 如果要添加项目,可以使用JavaScript的array.push()方法。
使用JavaScript对象存储值既然我注意到您想继续添加到数组中,则应考虑使用对象对数组中的数据进行分组。 var myArray = Array();
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");
}`
您应该做的是更改x和y的值。
var x = 0;
var y = 1;
var array = Array();
然后这将起作用。
array[x] = document.getElementById("cuna").value;
array[y] = document.getElementById("cuad").value;
但是我认为您不需要这样做。 您可以使用数组推送方法。
array.push(document.getElementById("cuna").value)
array.push(document.getElementById("cuad").value)
我认为您希望结果像这样:
[[cuna1,cuad1] [cuna2,cuad2]]
在这种情况下,您应该执行以下操作:
let arrayToPush = [document.getElementById("cuna").value,document.getElementById("cuad").value]
(顺便提一下,您在HTML中输入的是错字:“ cuda”而不是“ cuad”)
然后做
array.push(arrayToPush)
x = 0和y = 1的解决方案将不起作用,因为在第二轮中x将为1,y将为2,因此array [x]将覆盖先前的值。 但是,他们是正确的说法,您应该避免使用索引,而应该推送到数组。
您将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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.