2015-08-19 81 views
1

我在function創建對象:如何在javascript中動態命名對象中的元素?

createObject(attr) { 
    return { 
     attr: "test" 
    } 
} 

我希望attrfunction parameter命名。現在我結束了這個對象:

{ 
    attr: "test" 
} 

我該怎麼做?

+0

方括號標記 – sircapsalot

+1

可能的[此]重複(http://stackoverflow.com/questions/2462800/how-to-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable)and [this](https://stackoverflow.com/questions/695050/如何做我添加一個屬性到一個JavaScript對象使用一個變量名稱) – sircapsalot

回答

4

創建一個新對象並使用括號表示法來設置屬性。

function createObject(attr) { 
    var obj = {}; 
    obj[attr] = "test"; 
    return obj; 
} 
+0

:D ...我剛剛張貼t他同樣的答案:D(rofl)... –

0

這樣?

createObject(attrName) { 
    var obj = {}; 
    obj[attrName] = 'test'; 
    return obj; 
} 
2

我提出這個筆來展示如何來構造對象:

http://codepen.io/dieggger/pen/pJXJex

//function receiving the poarameter to construct the object 
var createObject = function(attr) { 
    //custom object with one predefined value. 
    var myCustomObject = { 
    anything: "myAnything", 
    }; 

//adding property to the object 
    myCustomObject[attr] = "Test"; 

//returning the constructed object 
    return myCustomObject; 

} 

//invoking function and assigning the returned object to a variable 
var objReturned = createObject("name"); 

//simple alert , to test if it worked 
alert(objReturned.name); 
相關問題