以另一个对象的属性为键的对象

编程入门 行业动态 更新时间:2024-10-27 23:31:10
本文介绍了以另一个对象的属性为键的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的对象:var myObj = {action1:0,action2:1,action3:2};

I have an object like this: var myObj = {action1:0, action2:1, action3:2};

测试功能从该列表中获取值作为参数,并且为了简化单元测试,我想在功能内部获取人类可读的标签

Test function gets values from this list as parameters and to simplify unit-testing I want to get human readable labels inside of the function

function myFunc(someaction, anotheraction, blablabla) { console.log("Action: " + arguments[0] + " then action: " + arguments[1]); //some code here }

所以在函数内部,我只能看到像0 1 2这样的值

So inside of the function I can see only values like 0 1 2

尝试解决方法,我试图创建像这样的新对象

Trying to workaround I tried to create new object like this

var dictObj = {myObj.action1:"action1", myObj.action2:"action2", myObj.action3:"action3"}

,然后将值解析为函数内部的名称:

and then resolve values to names inside of the function:

console.log("Action: " + dictObj[arguments[0]] + " then action: " + dictObj[arguments[1]]);

但是由于以下原因它不起作用

But it didn't work because of

'Uncaught SyntaxError: Unexpected token .'

如何重新编写此代码以获得可读的描述?

How I can rework this code to get readable description?

推荐答案

在ES5和更低版本中,您必须使用一系列语句来创建该对象:

In ES5 and earlier, you have to create that object with a series of statements:

var dictObj = {}; dictObj[myObj.action1] = "action1"; dictObj[myObj.action2] = "action2"; dictObj[myObj.action3] = "action3";

从ES2015(也称为"ES6")开始,您可以使用对象初始化程序中的计算属性名称来代替它:

As of ES2015 (aka "ES6"), you can do it with computed property names in the object initializer instead:

let dictObj = { [myObj.action1]: "action1", [myObj.action2]: "action2", [myObj.action3]: "action3" };

您可以使用 [] 中的任何表达式来创建属性名称.在这种情况下,这只是一个简单的属性查找.

You can use any expression within the [] to create the property name; in this case it's just a simple property lookup.

在两种情况下,请注意,没有 live 关系;如果将 myObj.action1 更改为42 以后,则完成上述操作后,它对 dictObj 中的属性名称没有任何影响.

In both cases, note that there's no live relationship; if you change myObj.action1 to 42 later, after doing the above, it doesn't have any effect on the property name in dictObj.

更多推荐

以另一个对象的属性为键的对象

本文发布于:2023-11-22 09:57:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!