我如何命名对象“键”?以编程方式在JavaScript中? [英] How can i name object "keys" programmatically in JavaScript?

查看:95
本文介绍了我如何命名对象“键”?以编程方式在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是我每天用Python做的事情。在JS中它不起作用,很可能是因为我吮吸JS。

What i want is something i do every day in Python. In JS it does not work, most probably because i suck in JS.

这是我想要的Python代码:

This is the Python code that would do what i want:

>key = 'just_a_key'
>value = 5
>dict = {key: value}
>dict
{'just_a_key':5}
>dict['just_a_key'}
5

这在JS中不起作用,关键是将命名为'key'。我知道这是因为我不是真的在这里创建一个字典,而是在编写相同代码时使用json创建一个对象。所以我现在的问题是:如何以编程方式在JS中命名对象keys(或属性?)?

This does not work in JS, the key there will be just named 'key'. I know this is because i'm not really creating a dictionary here, but using json to create an object when i write the same code. So my question now is: How can i programmatically name the objects "keys" (or properties?) in JS?

推荐答案

赞这个:

dict = {};

dict[key] = value;

JavaScript不会以对象文字符号计算属性名称的表达式,但如果使用对象成员运算符的方括号形式。

JavaScript does not evaluate expressions for property names in its object literal notation, but it does if you use the square bracket form of the object member operator.

MDN会员运营商

这篇关于我如何命名对象“键”?以编程方式在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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