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);
}
}
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);
}
$t to reference? It's hard to help unless we know the intent of that valueThe 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.
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
up+isupposed to be?up+i = function()isn't valid Javascript, that's why you get syntax errorup[i] = ...up+i, but you can dowindow['up' + i]. Though I don't recommend it