简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM