我可以将变量作为函数的参数吗? javascript
Can i have a variable as a parameter for a function? 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);
}
但这不起作用,因为我来自 ro(i) 的 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();
}
我正在尝试使用 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);
}
但这不起作用,因为我来自 ro(i) 的 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();
}