开发者

in javascript is it possible to construct an object literal with expressions evaluating to strings for property names? [duplicate]

This question already has answers here: How to use a variable for a key in a JavaScript object literal? 开发者_如何学运维 (16 answers) Closed 8 years ago.

i.e. is it possible to do this:

var fruit = "banana";
var x = {
    "app" + "le" : 5, // "apple" : 5
    function(){return "orange"} : 8, // "orange" : 8
    "" + fruit : 3 // "banana" : 3
};


No, you can't, you need to feed it after the first initialization :

var myKeyName = "bar";
x[myKeyName] = "foo";


You need to declare the empty object and build the strings after. An object literal expects valid strings for its names

If you don't run the function for 'orange' as well as define it, the name you want to be 'orange' will be the string of the entire function instead.

var fruit = "banana";
var x = {};
x["app" + "le"]=5;
x[(function(){return "orange"})()]=8;
x[fruit]=3;

/* returns  x={
    apple: 5,
    banana: 3,
    orange: 8
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜