[英]Using a for loop and document.getElementById to populate an array in Javascript
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;
获取这些值document.getElementById("spin " + i).value;
The ids
on my html for every input tag go from spin1 to spin18. 每个输入标签的html上的
ids
都从spin1转到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);
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看起来可编译,但这里有一些指针。
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
Having a js compiler that optimizes redundant code is sadly new feature. 拥有一个优化冗余代码的js编译器是一个可悲的新功能。 But still, why have two lines to maintain when you can have one.
但是,为什么还有两条线可以维持在一条线上。
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
The push method has an expensive overhead so use it with caution. 推送方法具有昂贵的开销,因此请谨慎使用。
The console has a built in logger, why not use that instead of an alert box? 控制台有一个内置的记录器,为什么不使用它而不是一个警告框?
console.log( nums.length );
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);
A couple of things to note: 有几点需要注意:
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/ 这对我有用 : http : //jsfiddle.net/sbqeT/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.