简体   繁体   English

动态添加属性到 object

[英]Dynamically add properties to object

In Javascript I created an object like this:在 Javascript 中,我创建了一个 object,如下所示:

this.view.objectExample.accessibilityConfig= {
    'propertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

I'm trying to add a new property in runtime but get "Cannot set properties of undefined" error.我正在尝试在运行时添加一个新属性,但出现“无法设置未定义的属性”错误。

Code used example:代码使用示例:

this.view.objectExample.accessibilityConfig.propertyD['flag'] = true;

What's the proper way to set a new property like this?设置这样的新属性的正确方法是什么?

Also tried like this:也试过这样:

this.view.objectExample.accessibilityConfig.propertyD.flag = true;

Because there is no propertyD in the original object, so accessibilityConfig.propertyD is undefined .因为原来的object中没有propertyD ,所以accessibilityConfig.propertyDundefined

You can dynamically add properties to an object, but that object has to exist first.您可以动态地将属性添加到 object,但 object 必须首先存在。 This is true for every level of an object's hierarchy.对于对象层次结构的每个级别都是如此。 So before you can do this:所以在你可以这样做之前:

this.view.objectExample.accessibilityConfig.propertyD.flag = true;

You'd have to do this:你必须这样做:

this.view.objectExample.accessibilityConfig.propertyD = {};

Or you can do both at the same time:或者你可以同时做这两个:

this.view.objectExample.accessibilityConfig.propertyD = { flag: true };

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

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