Javascript中对象文字的动态键好吧,我正在努力开发Nodes中的一个项目,我遇到了一个关于对象文字中的键的小问题,我有以下设置:var required = {
directories : {
this.applicationPath : "Application " + this.application + " does not exists",
this.applicationPath + "/configs" : "Application config folder does not exists",
this.applicationPath + "/controllers" : "Application controllers folder does not exists",
this.applicationPath + "/public" : "Application public folder does not exists",
this.applicationPath + "/views" : "Application views folder does not exists"
},
files : {
this.applicationPath + "/init.js" : "Application init.js file does not exists",
this.applicationPath + "/controllers/index.js" : "Application index.js controller file does not exists",
this.applicationPath + "/configs/application.js": "Application configs/application.js file does not exists",
this.applicationPath + "/configs/server.js" : "Application configs/server.js file does not exists"
}}好的,你们很多人都会看到它并认为它看起来没问题,但是编译器一直告诉我,我错过了一个:(冒号),我不是,它看起来像+或者.都在影响编译器。现在我相信(不确定),对象文字是在编译时创建的,而不是运行时,这意味着动态变量如this.applicationPath和连接不可用:( :(什么是克服这样的障碍而不必重写大块代码的最佳方法。
3 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
在对象文字中(ECMA-262§11.1.5称之为“对象初始化”),密钥必须是以下之一:
IdentifierName
字符串字面量
NumericLiteral
因此,您不能将表达式用作初始化器中的键。您可以使用带方括号表示法的表达式来访问属性。因此,要使用您必须执行的表达式设置属性:
var required = { directories : {}};required.directories[this.applicationPath] = "Application " + this.application + " does not exists";required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";...
等等。由于this.applicationPath
重用了很多,最好存储一个引用以帮助提高性能并减少代码量:
var a = this.applicationPath;var required = { directories : {}};var rd = required.directories;rd[a] = "Application " + this.application + " does not exists";rd[a + "/configs"] = "Application config folder does not exists";...
编辑
从ECMAScript ed 6开始,对象初始值设定项可以使用以下计算键:
[expression]: value
属性和方法名称也有简写语法。
请参阅MDN:对象初始化程序或ECMAScript§12.2.6。
添加回答
举报
0/150
提交
取消