简体   繁体   English

如何从这个复杂的JavaScript对象中访问值?

[英]How to access values from this complex JavaScript Object?

I am working with AbsoluteOrientationSensor 我正在使用AbsoluteOrientationSensor

I have an object that contains the values of the accelerometer of the phone. 我有一个包含手机加速度计值的对象。

The values that I need are nested inside an Symbol in the Object. 我需要的值嵌套在Object中的Symbol内。

How do I access those values? 我如何访问这些值?

The Object Name is "message". 对象名称是“消息”。

I have already tried this 我已经试过了

console.log(message.__sensor__.quaternion);

But I am getting the result as "undefined". 但我得到的结果是“未定义”。

I have never worked with the Symbol data type in JavaScript before. 我之前从未使用过JavaScript中的Symbol数据类型。

The Values that I want to access are the quaternion values 我想要访问的四元数值

This is the screenshot of the Object Structure - 这是对象结构的屏幕截图 -

我正在使用的对象

Thank you for your help. 谢谢您的帮助。

From the documentation : 文档

Properties 属性

OrientationSensor.quaternion : Returns a four element Array whose elements contain the components of the unit quaternion representing the device's orientation. OrientationSensor.quaternion :返回一个四元素Array,其元素包含表示设备方向的单位四元数的组件。

So: 所以:

console.log(message.quaternion);

You can also see in the screenshot that the object itself has a getter quaternion . 您还可以在屏幕截图中看到对象本身具有getter quaternion


I have never worked with the Symbol data type in JavaScript before. 我之前从未使用过JavaScript中的Symbol数据类型。

Symbols are used for various reasons as property names, but if they are used, it almost always means that you, as a consumer of the API, are not supposed to access that value directly. 符号由于各种原因用作属性名称,但如果使用它们,则几乎总是意味着您作为API的使用者不应该直接访问该值。 Instead you should use the "public" API the object provides to access this data, such as in this case. 相反,您应该使用对象提供的“公共”API来访问此数据,例如在这种情况下。

 function GetSymbol(object, name) { const string = `Symbol(${name})` return Object.getOwnPropertySymbols(object).find(symbol => symbol.toString() === string) } const __sensor__ = GetSymbol(message, "__sensor__") console.log(message[__sensor__]) 

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

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