Html 使用 for 循环和 document.getElementById 在 Javascript 中填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15470937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a for loop and document.getElementById to populate an array in Javascript
提问by Paul
I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;
我一直在尝试使用 for 循环填充数组并使用这些值 document.getElementById("spin " + i).value;
The ids
on my html for every input tag go from spin1 to spin18.
在ids
从SPIN1在我的HTML对于每个输入标签去spin18。
Any suggestions on what I am doing wrong? Or what I can change?
关于我做错了什么的任何建议?或者我可以改变什么?
var nums = [];
for(var i = 1; i <= 18; i++){
var num[i] = parseInt(document.getElementById("spin" + i).value);
nums.push(num[i]);
}
alert(nums.length);
回答by Dan
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.
问题是什么?您从不提及生成什么样的结果或前端 html 代码是什么样的。
The js looks compilable, but here are some pointers.
js 看起来可以编译,但这里有一些提示。
The number 0 is before 1
数字 0 在 1 之前
It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.
养成这种思维定势是一个好习惯,而且它可能会避免您以后犯愚蠢的错误。无论如何,为了加强这一点,下面是一个数字图表。
0 10 1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19
Avoid unnecessary variables
避免不必要的变量
Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.
可悲的是,拥有一个优化冗余代码的 js 编译器是一个新功能。但是,当您可以拥有一条生产线时,为什么还要维护两条生产线。
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
Don't push, insert
不要推,插入
The push method has an expensive overhead so use it with caution.
push 方法的开销很大,因此请谨慎使用。
Loggers
记录器
The console has a built in logger, why not use that instead of an alert box?
控制台有一个内置的记录器,为什么不使用它来代替警报框呢?
console.log( nums.length );
回答by PSR
try this
尝试这个
var nums = [];
for(var i = 1; i <= 18; i++){
var num= parseInt(document.getElementById("spin" + i).value);
nums.push(num);
}
alert(nums.length);
回答by bleakgadfly
A couple of things to note:
有几点需要注意:
- As PSR has mentioned, you use:
- 正如 PSR 所提到的,您使用:
var num[i]
when it should be
什么时候应该
var num
getElementById(id).value
only works for form elements, you have to use.innerHTML
for divs.
getElementById(id).value
仅适用于表单元素,您必须.innerHTML
用于 div。
This works for me: http://jsfiddle.net/sbqeT/