小编典典

Javascript中对象文字的动态键

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

好的,你们中的很多人都会看这个,并认为它没问题,但是编译器不断告诉我,我缺少一个:(冒号),但不是,好像+or或the .都在影响编译器。

现在我相信(不确定),对象文字是在编译时创建的,而不是在运行时创建的,这意味着动态变量(例如this.applicationPath和级联)将不可用

克服此类障碍而不必重写大量代码的最佳方法是什么。


阅读 515

收藏
2020-04-25

共1个答案

小编典典

您可以使用括号表示法设置动态键:

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
}
2020-04-25