Forum

> > Off Topic > [SOLVED] Javascript: Array Holding Functions Scope
Forums overviewOff Topic overviewLog in to reply

English [SOLVED] Javascript: Array Holding Functions Scope

No replies
To the start Previous 1 Next To the start

old [SOLVED] Javascript: Array Holding Functions Scope

Apache uwu
User Off Offline

Quote
In this example I'll be showing how I want Javascript to perform in Lua, then I'll show the code I have attempted in Javascript.

First, in Lua
1
2
3
4
5
6
7
8
9
10
11
12
ii={}
for i=1,5 do
	table.insert(
			ii,function()
				msg(i)
			end
		)
end

ii[1]()
i="test"
ii[1]()

This Lua script prints 1 and 1 after the other. √

Now in Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>

var ii=new Array();
for (i=1;i<5;i++) {
	ii.push(
		function() {
			alert(i);
		}
	);
}

ii[0]();
i="test";
ii[0]();

</script>

This, however prints 5 then test. ×

I realize it is because 'i' was declared in a global scope. I have searched online on how to define variables in different states but returned empty.

I would like to have the same return values in Lua for this Javascript.

Can anyone help me with this issue?

Edit:

I not sure if javascript scopes exist, but this method does not use local variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript">

var ii=new Array();

for (i=0;i<=5;i++) {
	ii[i]=function(value) {
		return function() {
			alert(value);
		}
         }(i);
}

ii[0]();
i="test";
ii[0]();
</script>

The problem was not push, but rather because I was using i globally when calling ii().
edited 2×, last 31.03.12 03:43:13 am
To the start Previous 1 Next To the start
Log in to replyOff Topic overviewForums overview