我是 JS 对象的新手。我有这样的代码
var foo = {
bar0: {
barr0: function() {//doo stuff}
barr1: function() {//doo stuff}
},
bar1: {
barr0: function() {//do stuff}
barr1: function() {//do stuff}
},
bar2: function() {//do stuff}
}
现在我有了这个变量 myVar
,它以它们将被调用的格式保存上述任何一个的“名称”。比如它可以有 bar0.barr1
或 bar2
或提及上述任何其他对象。 foo
不会成为 myVar
的一部分,因为它对每个调用都是通用的。一种可能的解决方案是使用 eval
,但我想尽可能避免使用它。
如果对象是一维的,我会使用 foo[myVar]()
但现在这是多维的,我不知道该如何调用它。
最佳答案
然后您需要应用一些脚本。
// define our access string and copy a reference from foo into level
var myVar = 'bar0.barr1',
level = foo;
// split that access string into an Array (splitted by dots) and loop over it
myVar.split(/\./).forEach(function( prop ) {
// if the property name ("bar0", "barr1") is available in our target object
if( prop in level ) {
// overwrite our level variable with the new object property reference, so somekind "climb up" the latter if we're dealing with nested objects
level = level[ prop ];
}
});
// if we're done, check if level holds a function reference and if so, execute it.
if( typeof level === 'function' ) {
level();
}
关于javascript - 动态调用带有子对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6994348/