2016-07-13 61 views
0

我有一個目標:如何動態地添加到對象中的JavaScript

var someObject={}; 

和我有一個功能,增加了對象:

function add(id, firstName){ 
    //stuff that makes sure id and firstName are correct format and stuff and say if firstName is john and id is I23423 
    someObject.id=firstName; 
} 

但它總是輸出

someObject{ 
    id="john" 
} 

但我想要的id是無論用戶輸入的id作爲,所以輸出將是

someObject{ 
    I23423="John" 
} 

我該如何添加/更改?

+0

http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-名稱爲 – epascarello

+0

是否指'someObject [id] = firstName;'? – bansi

回答

0

如果我明白你想要什麼,你需要在對象上使用[],就像它是一個數組。我真的不知道爲什麼,但這是你怎麼做的。

function(id,name){ 
 
    var obj = {}; 
 
    //whatever other things you need; 
 
    obj[id] = name; 
 
    return obj; 
 
    } 
 

相關問題