在Javascript中使用键值作为键值对中的键 [英] Use key's value as key in key-value pair in Javascript

查看:121
本文介绍了在Javascript中使用键值作为键值对中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中将键值对的值用作另一个键值对中的键?

How can you use the value of a key-value pair as the key in a different key-value pair in javascript?

我想执行以下操作:

var gizmos = {gizmo1: "G1"};
var things = {gizmos.gizmo1: "T1"};

因此本质上是相等的:

var things = {"G1": "T1"};

推荐答案

像这样:

var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1] = "T1";

无法将其作为对象初始化程序(也称为对象文字")的一部分来完成,因此必须在之后进行.

There's no way to do it as part of the object initializer (aka object "literal"), you have to do it after.

它起作用的原因是,在JavaScript中,您可以通过两种方式访问​​(获取或设置)对象上的属性:使用点分符号和 literal ,例如foo.bar,或使用方括号和 string ,例如foo["bar"].在后一种情况下,字符串不必是字符串文字,它可以是任何表达式的结果(在这种情况下,包括在另一个对象上的属性查找).

The reason it works is that in JavaScript, you can access (get or set) a property on an object in two ways: Either using dotted notation and a literal, e.g. foo.bar, or using bracketed notation and a string, e.g. foo["bar"]. In the latter case, the string doesn't have to be a string literal, it can be the result of any expression (including, in this case, a property lookup on another object).

侧面注意:如果在执行things[gizmos.gizmo1] = "T1";行后进行更改 gizmos.gizmo1,则不会更改things上的属性名称.没有持久的联系,因为gizmos.gizmo1 value 用于确定things[gizmos.gizmo1] = "T1";行中的属性名称(就像在其他任何表达式中一样).

Side Note: If you change gizmos.gizmo1 after you do the things[gizmos.gizmo1] = "T1"; line, it does not change the name of the property on things. There's no enduring link, because the value of gizmos.gizmo1 was used to determine the property name during the things[gizmos.gizmo1] = "T1"; line (just like it is in any other expression).

这篇关于在Javascript中使用键值作为键值对中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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