在 AS3 中组合/合并动态对象
我有 2 个动态对象,我想构建一个来包含所有属性:
var o1:Object = {prop1:val1,prop2:val2,prop3:val3};
var o2:Object = {prop3:val3a,prop4:val4};
并且我需要获得看起来像这样的第三个对象:
{prop1:val1, prop2:val2, prop3:val3a, prop4:val4};
基本上我需要一种方法来迭代对象属性并向第三个对象添加新属性。我不得不提的是,我对 AS3/Flash/Flex 还很陌生。
I have 2 dynamic objects and I want to build one to contain all the properties:
var o1:Object = {prop1:val1,prop2:val2,prop3:val3};
var o2:Object = {prop3:val3a,prop4:val4};
and I need to obtain a third object that looks like that:
{prop1:val1, prop2:val2, prop3:val3a, prop4:val4};
Basically I need a way to iterate through the object properties and to add new properties to the third object. I have to mention I'm quite new to AS3/Flash/Flex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个问题,你真的想在两个对象中都有 prop3 吗?您需要决定在发生此类碰撞时该怎么做,哪个对象优先。
其次,查看内省 api: http://livedocs .adobe.com/flex/3/html/help.html?content=usingas_8.html
类似这样的内容应该有效:
如果属性存在于 A 和 B 中,则 B 的属性将覆盖 A 的属性。另请注意,如果属性的值是对象,它将传递引用,而不是值的副本。在这些情况下,您可能需要克隆该对象,具体取决于您的需要。
注意:我还没有实际测试过上面的内容,但应该很接近。如果不起作用请告诉我。
已更新以修复错误。很高兴它对你有用。
First question, do you really mean to have prop3 in both objects? you will need to decide what to do in case of a collision like that, which object has precedence.
Secondly, check out the introspection apis: http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html
something like this should work:
If the property exists in A and B, B's will overwrite A's. Also note that if the values of a property is an object, it will pass a reference, not a copy of the value. You might need to clone the object in those cases, depending on your needs.
Note: I haven't actually tested the above, but it should be close. Let me know if it doesn't work.
Updated to fix the errors. Glad it works for you though.
您可以使用索引运算符动态访问/设置对象的属性。 for 循环将迭代属性名称,因此如果将它们放在一起,则以下测试将通过:
You can dynamically access/set properties on objects with the index operator. The
for
loop will itterate over the property names, so if you put it all together, the following test passes:您可以迭代对象属性,例如:
you can iterate over the object properties like: