例如,假设我使用节点分类来实现此功能:
function example(){
var exampleVar = nodes.classfication;
//below i use exampleVar to do calculations
.
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
但有时候说我想获得节点状态,所以我这样做:
function example(){
var exampleVar = nodes.status;
//below i use exampleVar to do calculations
.
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
我不想重复代码(在我的代码中)我想要重用的函数中有很多代码.因此,根据我想要从这个函数中获取的内容,我将它传递给函数,如下所示:
function example(thisAttribute){
var exampleVar = nodes.thisAttribute; //using the variable passed to the function
//below i use exampleVar to do calculations
.
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,我如何将对象属性作为参数传递给函数?我试过在网上看,但我不认为我正在寻找正确的东西,因为我找不到任何帮助.无论如何,提前谢谢:)
使用对象括号表示法:
function example(thisAttribute){
var exampleVar = nodes[thisAttribute];
}
Run Code Online (Sandbox Code Playgroud)