[SOLVED] Javascript: How to access the current index value inside an array stored function

Issue

If a function is stored in an array item, how can I gain access of the array’s current index value inside the function?
For example, how can I set my function in order to get results similar to this?

arr['hello'](); // function returns 'hello'
arr['world'](); // function returns 'world'
arr[123]() // function returns 123

Solution

Unless you know in advance which specific properties will be used, you’ll need a Proxy.

const prox = new Proxy(
  {},
  {
    get(_, prop) {
      return () => prop;
    }
  }
);

console.log(prox[123]());
console.log(prox.hello());    
console.log(prox['world']());

Since you have some non-numeric properties, you shouldn’t use an array.

Answered By – CertainPerformance

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.