“ for var in”访问JS对象会返回*自己*的所有属性?

时间:2019-01-23 15:30:43

标签: javascript

我在这里不知所措。谁能解释以下控制台输出的可能方式?为什么在label_multilanguage_key进行迭代时没有显示for var p in

    > Object.getOwnPropertyNames(design_element)
    (6) ["label_multilanguage_key", "value", "display_priority", "name", "help_text", "hidden"]

    > for (var p in design_element) console.log(p);
    VM226:1 value_type
    VM226:1 element_type
    VM226:1 requirement_setting
    VM226:1 multiple_values_setting
    VM226:1 user_enabled_setting
    VM226:1 grid_size_setting
    VM226:1 show_to_users
    VM226:1 disable_label
    undefined

    > console.log(design_element)
    VM262:1 
    {label_multilanguage_key: "&&mlkey_enable_filtering_for_id", value: false, display_priority: 6, name: "enable_filtering_for_id", help_text: "&&mlkey_proto_enable_filtering_help_text", …}
    display_priority: 6
    help_text: "&&mlkey_proto_enable_filtering_help_text"
    hidden: true
    label_multilanguage_key: "&&mlkey_enable_filtering_for_id"
    name: "enable_filtering_for_id"
    value: false
    __proto__: Object

    typeof(design_element)
    "object"

Re:有关如何创建这些对象的问题-确认需要花费较长时间,但应该使用类似的调用来创建

Object.create(element_structure.StaticTextField,{label_multilanguage_key:{value:ML_KEYS.first_name},name:{value:"first_name"}})

如果是这种情况,是否可能发生不可数的行为?还是在对象初始化过程中明显搞砸了?

2 个答案:

答案 0 :(得分:4)

  

对象初始化中是否明显搞砸了?

是的,将Object.create与属性描述符(例如Object.defineProperties)一起使用会创建non-enumerable properties by default。如果您不想做任何特别的事情,建议使用Object.assign代替第二个参数:

Object.assign(Object.create(element_structure.StaticTextField), {
    label_multilanguage_key: ML_KEYS.first_name,
    name: "first_name"
});

答案 1 :(得分:0)

尝试在循环中检查hasOwnProperty

for (var p in design_element) {
    if (design_element.hasOwnProperty(p)) console.log(p);
}