简体   繁体   English

JavaScript常量和对象文字

[英]JavaScript constants and object literals

I know I can do this in JavaScript: 我知道我可以用JavaScript做到这一点:

RequestDate: {
    '0' : 'previous_activity_date',
    '1': 'next_activity_date'
  }

And I can do this: 我可以这样做:

this.RequestDate = {};
this.RequestDate[App.FORWARD] = 'next_activity_date';
this.RequestDate[App.BACK] = 'previous_activity_date';

Is there a way of making the following work: 有没有一种方法可以使以下工作:

RequestDate: {
    App.Back : 'previous_activity_date',
    App.Forward: 'next_activity_date'
  },

The above obviously errors, is there a way to make it work? 以上明显的错误,有没有办法使它起作用?

you can do this. 你可以这样做。

RequestDate: {
    [App.Back]: 'previous_activity_date',
    [App.Forward]: 'next_activity_date'
  }

Short answer: no. 简短的回答:不。 You can only have literal keys in the object literal. 对象文字中只能有文字键。 Your own solution is the best one if you want to use constants. 如果要使用常量,您自己的解决方案是最佳解决方案。

http://bclary.com/2004/11/07/ http://bclary.com/2004/11/07/

11.1.5 Object Initialiser 11.1.5对象初始化器

An object initialiser is an expression describing the initialisation of an Object, written in a form resembling a literal. 对象初始化程序是一种描述对象初始化的表达式,以类似于文字的形式编写。 It is a list of zero or more pairs of property names and associated values, enclosed in curly braces. 它是用大括号括起来的零或更多对属性名称和关联值的列表。 The values need not be literals; 这些值不必是文字。 they are evaluated each time the object initialiser is evaluated. 每次评估对象初始化程序时都会对它们进行评估。

As you have noticed, you can write this: 如您所见,您可以这样编写:

RequestDate = {};
RequestDate[App.Back] = 'previous_activity_date';
RequestDate[App.Forward] = 'next_activity_date';

But the javascript syntax does not allow an expression before the : of the JSON notation. 但是javascript语法不允许在JSON表示法的:之前使用表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM