简体   繁体   English

创建具有可变属性的对象

[英]Creating objects with variable properties

I'm trying to do this: 我正在尝试这样做:

var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {sortAfter: ascending};

But a console.log(sorted) output the following object: 但是console.log(已排序)输出以下对象:

{ sortAfter: -1 }

It's like the first variable is not used in the object creation... 就像第一个变量没有在对象创建中使用...

Question: How do i get the object to be made of two variables, and not one variable and one fixed string? 问题:如何使对象由两个变量组成,而不是由一个变量和一个固定字符串组成?

try this way: 尝试这种方式:

var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {};
sorted[sortAfter] = ascending;

In object literals, the keys are always literals, they're never variables. 在对象文字中,键始终是文字,它们决不是变量。 If you want to set a dynamic object key, you'll have to do it like this: 如果要设置动态对象键,则必须这样做:

var sorted = {};
sorted[sortAfter] = ascending;

Use the subscript/bracket notation: 使用下标/括号表示法:

var sorted = {};
sorted[sortAfter] = ascending;

The subscript operator will convert its operand to a string, 下标运算符会将其操作数转换为字符串,

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

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