使用常量作为Javascript关联数组的索引 [英] Using constants as indices for Javascript Associative Arrays

查看:89
本文介绍了使用常量作为Javascript关联数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JS中创建一个关联数组,但是使用定义为类的一部分的常量作为索引。

I'm looking to create an associative array in JS, but use constants defined as part of the class as indices.

我想要的原因是这样的该类的用户可以使用常量(定义事件)来触发操作。

The reason I want this is so that users of the class can use the constants (which define events) to trigger actions.

一些代码来说明:

STATE_NORMAL = 0;
STATE_NEW_TASK_ADDED = 0;
this.curr_state = STATE_NEW_TASK_ADDED;

this.state_machine = {
    /* Prototype:
    STATE_NAME: {
        EVENT_NAME: {
            "next_state": new_state_name,
            "action": func
        }
    }
    */

    STATE_NEW_TASK_ADDED : { // I'd like this to be a constant
        this.EVENT_NEW_TASK_ADDED_AJAX : {
            "next_state": STATE_NEW_TASK_ADDED,
            "action" : function() {console.log("new task added");},
        }
    }
}

// Public data members.
// These define the various events that can happen.
this.EVENT_NEW_TASK_ADDED_AJAX = 0;
this.EVENT_NEW_TASK_ADDED_AJAX = 1;

我无法解决此问题。我对JS不太好,但看起来无论我做什么,数组都是用字符串而不是常量定义的。有没有办法强制数组使用常量?

I'm having trouble getting this to work. I'm not too great with JS, but it looks like no matter what I do, the array gets defined with strings and not constants. Is there any way to force the array to use the constants?

谢谢!

推荐答案

实际上,这里的问题是,当你定义一个字面对象时,你不能使用关键部分的值。

The problem here, actually, is that you can't use a value for the key part when you're defining an object literally.

也就是说,它使用预期的常量值:

That is to say, this uses the constant values as expected:

var CONSTANT_A = 0, CONSTANT_B = 1;
var state_machine = {};
state_machine[CONSTANT_A] = "A";
state_machine[CONSTANT_B] = "B";
console.log(state_machine[0]); // => A
console.log(state_machine[1]); // => B

但这不会按预期工作,而是使用字符串 CONSTANT_A 作为键:

But this won't work as expected, instead using the string CONSTANT_A as key:

var CONSTANT_A = 0, CONSTANT_B = 1;
var state_machine = {
    CONSTANT_A: "A",
    CONSTANT_B: "B",
};
console.log(state_machine[0]); // => undefined
console.log(state_machine["CONSTANT_A"]); // => A
console.log(state_machine.CONSTANT_A); // => A

JavaScript有一个简写来定义对象文字,你可以省略键周围的双引号。表达式不能使用,因此 CONSTANT_A 将不会被评估。

JavaScript has a shorthand to define object literals where you can omit the double-quotes around keys. Expressions can't be used, so CONSTANT_A won't be evaluated.

另请参阅@ Kristian的答案:ES6 /现代JS,基本上可以实现你想要的东西。

See also @Kristian's answer below re: ES6/modern JS, essentially making what you want possible.

这篇关于使用常量作为Javascript关联数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆