Question about loop in javascript
I tried this loop, but isn't working (Syntax errors). What is the correct way to do it? up+i doesn't work for example.
for(i=0;i<10;i++) {
up+i = function() {
base.refresh("Field"+i, $t+i);
开发者_Go百科 }
}
The primary issue is around this line
up+i = function() {
The expression up+i
produces a value, not a variable, and a place which can be assigned to. Were you trying instead to assign into an array? If so change it to the following
up[i] = function() {
EDIT
OP clarified that the intent is to create 10 named functions. In that case there needs to be an object to hang them off of. I'll call it root for an example
var root = {};
for (i = 0; i < 10; i++) {
root['up' + i] = function() {
base.refresh("Field"+i, $t+i);
};
}
Additionally right now the function is capturing a single i
meaning all instances of the function will have the same value for i
. To prevent this use a separate function to capture the value.
var root = {};
for (i = 0; i < 10; i++) {
root['up' + i] = function(arg) {
return function() { base.refresh("Field"+arg, $t+arg); };
} (i);
}
The code responsible for looping works. Just see here: http://jsfiddle.net/7aZLv/ (warning! opens 10 alert boxes one after another)
EDIT:
You can create global functions like that: http://jsfiddle.net/7aZLv/1/
for(i=0;i<10;i++) {
window['up'+i] = function(){
alert('test');
}
}
up3(); // will make alert appear
The error happened because you assignment expression was incorrect (you assigned value to expression, not a variable how it should be assigned).
Maybe it should just be
for(i=0;i<10;i++) {
up = function() {
base.refresh("Field"+i, $t+i);
}
}
? We need lots of information to help you, what is up supposed to be, what are you trying to accomplish? What syntax errors are you getting?
You cannot have an expression on the left hand side of an assignment. is up+i
supposed to be pointer arithmetic? if so, there are no pointers in javascript. i cannot tell what you are trying to do, but the first thing to do would be to change up+i = function() { ...}
to up = function() {...}
or else get a new variable to assign it too.
Many errors in your code.
up is string? $t what is this?
maybe like this?
for(i=0;i<10;i++) {
var new_func = 'up' + i;
new_func = function() {
base.refresh("Field"+i, $t+i);
}
}
Instead of trying to create individual variables for the functions, you can add them to an array.
var ups;
for(i=0;i<10;i++) {
ups.push(function() {
base.refresh("Field"+i, $t+i);
});
}
try this
for(i=0;i<10;i++) {
window["up" +i] = function() {
base.refresh("Field"+i, $t+i);
}
}
This will add the functions to the window
object so that you can make calls like this after it:
up0();
up1();
// etc
精彩评论