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

时间:2015-05-14 14:32:04

标签: javascript jquery

例如,假设我使用节点分类来实现此功能:

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
    .
    .
    .
    .
    }

这不起作用,如何将对象属性作为参数传递给函数?我试过在网上看,但我不认为我正在寻找正确的东西,因为我找不到任何帮助。无论如何,提前谢谢:)

1 个答案:

答案 0 :(得分:5)

使用object bracket notation

function example(thisAttribute){
  var exampleVar = nodes[thisAttribute];
}
相关问题