Javascript: How to access the current index value inside an array stored function Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript: How to access the current index value inside an array stored function without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

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.

We are here to answer your question about Javascript: How to access the current index value inside an array stored function - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji