[英]JavaScript: For-Loop does not run?
Why the for loop does not run? 为什么for循环不运行?
countfiles
return a whole number 函数countfiles
返回整数 parseInt(countfiles())
also not work too parseInt(countfiles())
也不起作用 Here my Code: 这是我的代码:
function set_default_value() {
var element = document.getElementsByName('fields');
for (var i = countfields(); i < element.length; ++i) {
element[i].value = "default";
}
}
Why does not run? 为什么不运行?
EDIT: 编辑:
Here's the function countfields
这是函数countfields
function countfields() {
var field_counter = 0;
for (var i = 0; i < 50; i++) {
if (typeof document.getElementsByName('other_fields')[i] != "undefined") {
var field_counter = field_counter + 1;
}
}
return field_counter;
}
@varunachar touched on the issue in one of his comments: @varunachar在他的评论之一中谈到了这个问题:
The number returned by countfields could be greater than element.length countfields返回的数字可能大于element.length
In this line: 在这一行:
for (var i = countfields(); i < element.length; ++i)
Read this i < element.length
as "as long as i
is less than element.length
, do stuff" . 将此i < element.length
读为“只要i
小于element.length
,就可以做” 。 Or, if countfields()
is equal or greater, nothing happens. 或者,如果countfields()
等于或更大,则什么也不会发生。
1 other_fields
: http://jsfiddle.net/D5ZHV/ works 1个其他other_fields
: http : //jsfiddle.net/D5ZHV/作品
6 other_fields
: http://jsfiddle.net/Ay6BN/ does not work 6个other_fields
: http://jsfiddle.net/Ay6BN/ 不起作用
Change 更改
var field_counter = field_counter + 1;
To 至
field_counter = field_counter + 1;
In countfields()
function. 在countfields()
函数中。 You are declaring field_counter
inside the for loop which is wrong 您在for循环中声明了field_counter
这是错误的
function countfields() {
var field_counter = 0;
for(var i = 0; i < 50; i++) {
if(typeof document.getElementsByName('other_fields')[i] != "undefined") {
var field_counter = field_counter + 1; } }
return field_counter; }
var always define the scope of the variable. var始终定义变量的范围。 Inside the if doing var field_counter
will create a variable with scope inside the if-statement. 在if变量内, var field_counter
将在if语句内创建一个范围为变量的变量。
you should write as 你应该写成
field_counter = field_counter + 1;
If you test your countfields() it should always return 0; 如果您测试countfields(),它将始终返回0;否则,返回0。
Also try doing console.log(elements)
也尝试做console.log(elements)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.