0

Given an array of self-contained JavaScript functions is there a way to access their respective indexes from within the function code? I would like to avoid having to hard-code those indexes in the function code:

var testArr = [
(function(){return 0})(),
(function(){return 'how to return/access ARRAY INDEX (=1)??'})()
]


console.log(testArr[0]) // 0
console.log(testArr[1]) // how to return/access ARRAY INDEX (=1)??
Gonki
  • 567
  • 1
  • 8
  • 17
  • 1
    This seems like an XY problem. What are you actually trying to accomplish (as a larger goal)? – royhowie Mar 08 '15 at 08:23
  • There needs to be an IF statement in the function code using array index of that function (which function was run last time) – Gonki Mar 08 '15 at 08:37
  • Why don't you store whichever function was run last time in another variable, e.g., `var lastIndex;`. Then, whenever you call a function, you can update its value. – royhowie Mar 08 '15 at 08:39
  • Yes, I do store which fn was run. How would I write in function[1] for example "if (lastIndex === 1)" where "1" is self-index? – Gonki Mar 08 '15 at 08:41
  • I'm still interested in what your larger goal is. Why are you storing these self-executing functions in an array? There might be an easier way to approach whatever you're trying to accomplish. If you explained in a little more detail what exactly you're trying to do (besides access the array index of a given function), we might be able to help you further. – royhowie Mar 08 '15 at 08:44
  • It's part of a rather complex (for posting the code here) mechanism that dynamically generates form fields depending on which object a user selects in GUI. Those functions return sets of form fields. There is a large set of those functions and each GUI object has a subset of them. Each of those functions in turn performs different tasks on what a user did with form fields. That's where I need to know array index of the function inside the function. All works well there except I have to hard-code those values. I'm ready to consider object vs. array (associative array) if that would help. – Gonki Mar 08 '15 at 08:50
  • perhaps you could use a closure with a generator function (not referring to the ES6 harmony proposal): `var gen = function (index, fn) { return fn; }`. Now, you can call `var bettetFn = gen(5, myFunction)`, and `betterFn` will be aware of the value of `index`. – royhowie Mar 08 '15 at 09:08
  • perhaps this is most elegant: fn code "(function(idx){return idx})" and call it like so "testArr[0](0)" – Gonki Mar 08 '15 at 09:25

1 Answers1

0

Having analyzed different options I think this one is the most appropriate (without immediate invocation of self-contained function + passing array index into function arguments)

var testArr = [
(function(idx){return idx}),
(function(idx){return idx * 2})
]

console.log(testArr[0](0)) // 0
console.log(testArr[1](1)) // 2
Gonki
  • 567
  • 1
  • 8
  • 17