如何将多个值赋给一个数组并将它们相加?
我已经实现了这个,但由于我不熟悉 FOR 循环语句,我已经这样做了,如下所示! 您能帮我使用 FOR 循环语句缩短这段代码并解释一下它是如何工作的吗!谢谢
这是我的代码:
var inputs = new Array();
inputs["a"] = document.getElementById("a").value;
inputs["b"] = document.getElementById("b").value;
inputs["c"] = document.getElementById("c").value;
inputs["d"] = document.getElementById("d").value;
inputs["e"] = document.getElementById("e").value;
然后我将它们添加为:
var inputsvalue = inputs["a"] + inputs["b"] + inputs["c"] + inputs["d"] + inputs["e"];
请注意,我正在添加每个输入字段的值并将它们分配给一个变量!
例如,假设输入字段 a、b、c、d、e 的值如下:
1, 2, 3, 4, 5
所以我希望将它们分配给变量“inputsvalue”,例如:
var inputsvalue = "12345";
这就是我添加的原因他们就是这样!那么有没有其他方法可以做到这一点!在此示例中,我只有 5 个输入字段,但如果有大约 100 个输入字段怎么办!
本题的目的是了解本例中FOR循环语句是如何工作的!
提前致谢! :)
I've already implemented this, but as I'm not familiar with the FOR loop statement I've done it this way as shown below!
Can you please help me shorten this code using the FOR loop statement and explain me how this works! Thanks
Here is my code:
var inputs = new Array();
inputs["a"] = document.getElementById("a").value;
inputs["b"] = document.getElementById("b").value;
inputs["c"] = document.getElementById("c").value;
inputs["d"] = document.getElementById("d").value;
inputs["e"] = document.getElementById("e").value;
And then I've added them up as:
var inputsvalue = inputs["a"] + inputs["b"] + inputs["c"] + inputs["d"] + inputs["e"];
Note that I'm adding the value of each input field and assigning them into a variable!
For example lets say the values for input fields a, b, c, d, e are as follows:
1, 2, 3, 4, 5
So I want them to be assigned to the variable "inputsvalue" like:
var inputsvalue = "12345";
That's why I added them like that! So is there any other way to do this! In this example I only have 5 input fields, but what if there was about 100 input fields!
The purpose of this question is to learn how FOR loop statement works in this example!
Thanks in advance! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以使用
You can use
更好的方法是将每个输入的 id 命名为:
id="element0"
,或者通常为:id="element"
这样你就可以去:
A better way to do this is to name each input's id something like:
id="element0"
, or generally:id="element<n>"
This way you could go: