Javascript:如何访问数组存储函数中的当前索引值



如果函数存储在数组项中,如何访问函数中数组的当前索引值
例如,如何设置函数以获得类似的结果?

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

除非您事先知道将使用哪些特定属性,否则您将需要一个Proxy。

const prox = new Proxy(
{},
{
get(_, prop) {
return () => prop;
}
}
);
console.log(prox[123]());
console.log(prox.hello());    
console.log(prox['world']());

由于您有一些非数字属性,因此不应该使用数组。

最新更新