首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript中用于对象文字的动态键

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

Stack Overflow用户
提问于 2018-03-19 08:02:36
回答 2查看 0关注 0票数 0

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

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

EN

Stack Overflow用户

发布于 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
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档