我可以用一个变量作为函数的参数吗?javascript



我正试图使用javascript中的函数进行40次循环。

我就是这么做的:

var i;
setTimeout(function ro(i) {
if (i % 5 == 0) {
currentIndex = 0;
}
if (i % 5 == 1) {
currentIndex = 1;
}
if (i % 5 == 2) {
currentIndex = 2;
}
if (i % 5 == 3) {
currentIndex = 3;
}
if (i % 5 == 4) {
currentIndex = 4;
}
document.getElementById('radio' + currentIndex).click();
if (currentIndex == 5) {
currentIndex = 0
}
}, 2000);
for (var i = 0; i < 200; i++) {
ro(i);
}

但这不起作用,因为我的i from ro(i(是一个新参数,我试图在任何地方使用相同的i。有办法做到这一点吗?非常感谢。

您需要做的不是将i作为参数传递,而是保持它的全局性。您可以简单地通过在范围外定义它(比如在代码的顶部(,然后通过简单地调用它的名称(在本例中为i(在函数中使用它来实现这一点。以下是修改后的代码:

var i;
setTimeout(function ro() {
if (i % 5 == 0) {
currentIndex = 0;
}
if (i % 5 == 1) {
currentIndex = 1;
}
if (i % 5 == 2) {
currentIndex = 2;
}
if (i % 5 == 3) {
currentIndex = 3;
}
if (i % 5 == 4) {
currentIndex = 4;
}
document.getElementById('radio' + currentIndex).click();
if (currentIndex == 5) {
currentIndex = 0
}
}, 2000);
for (i = 0; i < 200; i++) {
ro();
}

最新更新