说我有这个功能签名:
export const readVariableProps = function(obj: Object, props: Array<string>) : any {
// props => ['a','b','c']
return obj['a']['b']['c'];
}
显然,props是一个可变长度的数组,具有未知列表或要从给定对象读取的属性。
是使用
eval()
获得这种动态行为的唯一方法?我怎样才能做到这一点?
最佳答案
要获得等价于return obj['a']['b']['c'];
的值,其中'a'
,'b'
和'c'
是问题中显示的数组中的值,可以执行以下操作(您可能必须将一些详细信息转换为typeScript) :
export const readVariableProps = function(obj: Object, props: Array<string>) : any {
return props.reduce(function(prior, next) {
return prior[next];
}, obj);
}
仅供参考,这种情况正是
.reduce()
设计的目的-累积通过访问数组中的每个项目而构建的值。
如果数组中的最后一个属性不存在,则会抛出该异常。
关于javascript - 从对象读取可变数量的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46387643/