简体   繁体   English

在Javascript object / json中使用变量会产生编译错误

[英]Using a variable in Javascript object/json produces compile error

First time working with javascript and JSON. 第一次使用javascript和JSON。 Curious why this causes a comiler error: 奇怪为什么这会导致编译错误:

var dataTypes = new function() {
    this.list = "list"; this.boolean = "boolean";
};  

var jsonDataTypes = [
        {dataTypes.list:"Food For Lunch"}
];

When this doesn't. 如果不是这样。

var dataTypes = new function() {
    this.list = "list"; this.boolean = "boolean";
};  

var jsonDataTypes = [
        {"Food For Lunch":dataTypes.list}
];

Why am I allowed to use a variable for the value but not for the key? 为什么我允许使用变量作为值而不是键?

The error is: 错误是:

Multiple markers at this line
    - Missing semicolon
    - Syntax error on token(s), misplaced 
     construct(s)
    - Missing semicolon
    - Syntax error on tokens, delete these 
     tokens

First, you are working with JavaScript objects, not JSON. 首先,您正在使用JavaScript对象,而不是JSON。 Objects are a data type in JavaScript, whereas JSON is a data transfer format. 对象是JavaScript中的数据类型,而JSON是数据传输格式。

The keys inside object literals must be valid identifiers, strings or numbers, because keys are interpreted literally . 对象文字中的键必须是有效的标识符,字符串或数字,因为键是按字面意义解释的。 Identifiers are not allowed to have dots ( . ) and certain other characters in it. 标识符中不能包含点( . )和某些其他字符。 See the specification for more information. 有关更多信息,请参见规范

As you want to use the value of dataTypes.list as key, you have to create the object in two steps: 如果要使用dataTypes.list的值作为键,则必须分两个步骤创建对象:

var jsonDataTypes = [{}];
jsonDataTypes[0][dataTypes.list] = "Food For Lunch";

or if you want to use it literally, use a string: 或者,如果您想直接使用它,请使用字符串:

var jsonDataTypes = [
    {"dataTypes.list": "Food For Lunch"}
];

Because of the JS syntax. 由于JS语法。 But you can do the following: 但是您可以执行以下操作:

var jsonDataTypes = [{}];

jsonDataTypes[0][dataTypes.list] = "Food For Lunch";

JavaScript object syntax does not allow for evaluation of the Key . JavaScript对象语法不允许评估Key I suppose you could do the following: 我想您可以执行以下操作:

var jsonDataTypes = [];
var obj = {};
obj[dataTypes.list] = "Food For Lunch";
jsonDataTypes.push(obj);

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

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