Javascript中用于对象文字的动态键

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (20)

好的,我正在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连接和串联)将不可用:( :(

在不必重写大块代码的情况下,克服这种障碍的最佳方法是什么?

提问于
用户回答回答于

您可以设置动态键的唯一方法是使用括号表示法:

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
}
用户回答回答于

在对象文本中(ECMA-262§11.1.5称它为“对象初始化程序”),键必须是以下之一:

  1. IdentifierName
  2. 字符串字面量
  3. 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

还有属性和方法名称的简写语法。

扫码关注云+社区