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

早过忘川 提交于 2019-11-27 08:51:42

问题


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

回答1:


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

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



回答2:


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
}


来源:https://stackoverflow.com/questions/1783403/in-javascript-is-it-possible-to-construct-an-object-literal-with-expressions-eva

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!