Javascript 中对象文本的动态键

2022-08-30 05:40:08

好吧,所以我正在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和它们都影响了编译器。:+.

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

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


答案 1

ECMAScript2015 中支持计算属性名称:

var name = 'key';
var value = 'value';
var o = {
  [name]: value
};
alert("o as json : " + JSON.stringify(o));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer


答案 2

在 ECMAScript 2015(第 6 版)之前,对象文本(ECMAScript 称之为“对象初始值设定项”)键必须是以下之一:

  1. 标识符名称
  2. StringLiteral
  3. 数字文体

因此,您不能在初始值中使用表达式作为键。这在 ECMAScript 2015 中已更改(见下文)。您可以使用带有方括号表示法的表达式来访问属性,因此要使用表达式设置属性,您必须执行以下操作:

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 2015 (ed 6) 开始,对象初始值设定项可以使用以下命令计算密钥:

[expression]: value

还有属性和方法名称的速记语法。

请参阅 MDN:对象初始值设定项ECMAScript 对象初始值设定项