[turboid] javascript solutions

Home     Contact     Search     About me
Arrays
20 Dec 2011

Let a function know its array index

Easy usable solution

Sometimes there are challenges in JavaScript which seem to be very simple in the first moment, then impossible to solve in the second moment, until you get a code snippet with a surprisingly short solution from a versed developer. This is such a case.

Ever asked yourself how to make each function in a functions array "know" which array index it is placed at? The following example won't work:

	var fncArr = [];

	for(var i = 0; i < 10; i++){
		fncArr[i] = function(){ alert(i); };
	}
	
	fncArr[8]();

Instead of 8 it will show 10.

Many people think it is impossible to solve this problem. But fortunately, a long time ago a versed forum member in a german JavaScript forum gave me a code snippet similar to the following one:

	fncArr = [];
	
	for(var i = 0; i < 10; i++){
		fncArr[i] = function(x){ return function(){ alert(x); };}(i);
	}
	
	fncArr[8]();

And it works fine!


Comments

Add comment:

Name: (required)
E-Mail: (required, remains invisible)
Website:
Comment:
Please check all (anti-spam):