好的,我正在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
连接和串联)将不可用:( :(
在不必重写大块代码的情况下,克服这种障碍的最佳方法是什么?
发布于 2018-03-19 16:14:44
您可以设置动态键的唯一方法是使用括号表示法:
required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";
(当然,无论你做这个定义,都this.applicationPath
必须存在)
但你需要this.applicationPath
在钥匙?你如何获取这些值?也许你可以this.applicationPath
从你用来访问属性的任何值中删除。
但如果你需要它:
如果您想避免重复大量代码,可以使用数组来初始化密钥:
var dirs = ['configs', 'controllers', ...];
var files = ['init.js', 'controllers/index.js', ...];
var required = { directories: {}, files: {} };
required.directories[this.applicationPath] = "Application " + this.application + " does not exists";
for(var i = dirs.length; i--;) {
required.directories[this.applicationPath + '/' + dirs[i]] = "Application " + dirs[i] + " folder does not exists";
}
for(var i = files.length; i--;) {
// same here
}
https://stackoverflow.com/questions/-100003641
复制相似问题