【问题标题】:dynamically call an object with sub objects动态调用带有子对象的对象
【发布时间】:2011-08-09 09:54:51
【问题描述】:

我是 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.barr1bar2 或提及上述任何其他对象。 foo 不会成为 myVar 的一部分,因为它在每个呼叫中​​都很常见。一种可能的解决方案是使用eval,但我想尽可能避免使用它。

如果对象是一维的,我会使用foo[myVar](),但现在它是多维的,我不知道该如何称呼它。

【问题讨论】:

    标签: javascript object


    【解决方案1】:

    然后你需要应用一些脚本。

    // 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();
    }
    

    【讨论】:

    • 能否请您添加一些 cmets 来描述上述代码的作用?我应该把它包装成一个函数吗?因为我需要多次调用它..
    • 这将如何与第三维度及其他维度一起工作?据我了解,它会用每个额外的“维度”覆盖level var,所以在bar0.barr0.barrr0 level 将是barr0['barrr0'] .. 但它必须是bar[barr0][barrr0] 对吗?
    • Not all browsers 了解 forEach。
    • 哦 okiee.. 没关系.. 它用之前的 level 替换了 level + 新道具。非常感谢......它就像一个魅力:D
    • @whitequark 不用担心.. 它适用于需要最低版本 13 的 chrome 应用程序;)
    【解决方案2】:

    多维没有区别,一直加方括号即可:

    foo[myVar][myvar2]()
    

    编辑:没关系,误解了这个问题,这很讽刺,因为我实际上几乎完全问了这个问题!

    In javascript how can I dynamically get a nested property of an object

    【讨论】:

    • 我不能...... myVar 只是一个具有所有对象级别的变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2012-11-12
    相关资源
    最近更新 更多