简体   繁体   English

如何获取特定 Javascript 属性的名称?

[英]How to get the name of a specific Javascript property?

Given a Javascript object with the method myobject.mymethod the name of the method can be retrieved for printing or whatever using myobject.mymethod.name .给定带有方法myobject.mymethod的 Javascript object ,可以使用myobject.mymethod.name检索方法的名称以进行打印或任何其他操作。

How do I achieve the same thing for property myobject.myproperty .如何为属性myobject.myproperty实现相同的目标。

UPDATE: Specific scenario.更新:特定场景。

I have an object from a third party library that defines a load of constant values used throughout its api我有一个来自第三方库的 object,它定义了在其 api 中使用的常量值的负载

obj = {
  CONST1 = 1;
  CONST2 = 2;
  CONST3 = 3;
  // ...
}

I'm handling events that are called with these values and want to log what each event is called with.我正在处理使用这些值调用的事件,并希望记录每个事件被调用的内容。 The raw values aren't useful in a log, so I want to log the constant names, ideally without a switch statement mapping values to hardcoded strings or having to define my own lookup table.原始值在日志中没有用,所以我想记录常量名称,理想情况下不需要 switch 语句将值映射到硬编码字符串或必须定义我自己的查找表。

The library object has a load of other crap defined on it too, so just looking up the property using the value is not a reliable solution.库 object 还定义了许多其他垃圾,因此仅使用该值查找属性并不是一个可靠的解决方案。

You can list your properties with Object.keys().您可以使用 Object.keys() 列出您的属性。 So for example if you need list of props with their values, you can do something like this:因此,例如,如果您需要道具列表及其值,您可以执行以下操作:

 let a = {prop: "foo"}; console.log( Object.keys(a) ); // prints all prop names Object.keys(a).map( (i) => console.log("property:", i, " has value: ", a[i]) ); // prints all props with corresponding values

Updated answer: Use debugger to find out which values are used inside program.更新答案:使用调试器找出程序内部使用了哪些值。 https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints

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

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