如何将对象的属性作为参数传递?

3
例如,假设我有一个使用节点分类的函数:
function example(){

var exampleVar = nodes.classfication;

//below i use exampleVar to do calculations
.
.
.
.
}

但是有时候我想获取节点的状态,所以我会这样做:

function example(){

    var exampleVar = nodes.status;

    //below i use exampleVar to do calculations
    .
    .
    .
    .
    }

我不想重复编写代码,因为在我的函数中有很多代码需要重复使用。所以根据我想要从这个函数中获取什么,我会像这样将它传递给函数:

function example(thisAttribute){

    var exampleVar = nodes.thisAttribute; //using the variable passed to the function

    //below i use exampleVar to do calculations
    .
    .
    .
    .
    }

这不能正常工作,如何将对象属性作为参数传递给函数?我尝试在网上查找,但我认为我没搜到正确的信息,因为我找不到任何帮助。无论如何,提前致谢 :)

相关问题,可能有重复:JavaScript属性访问:点表示法与括号表示法? - James Thorpe
1个回答

5
使用对象括号表示法进行操作:

对象括号表示法

function example(thisAttribute){
  var exampleVar = nodes[thisAttribute];
}

1
啊,非常好,我不知道那个。非常感谢:D - thatOneGuy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接