1. ホーム
  2. javascript

[解決済み] Javascriptのオブジェクトリテラルの動的キー [重複]。

2022-11-10 02:30:24

質問

私は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
}