如何获取对象 a 拥有的所有属性(可枚举的、不可枚举的,不包括继承来的属性)


// 一、获取可枚举的属性
    var arr = ['a','b','c']
    console.log(Object.keys(arr))

    //二、获取可枚举和不可枚举属性
    var my_obj = {
      getFoo:{
        value:function (){return this.value},
        enumerable:false
      }
    }
    my_obj.foo = 1
    console.log(Object.getOwnPropertyNames(my_obj).sort())

    // 三、获取不可枚举的属性
    var cat = {
      name:"猫",
      age:2
    }
    Object.defineProperty(cat,'sound',{
      enumerable:false,
      configurable:false,
      writable:false,
      value:false
    })
    var target = cat
    var enum_and_noenum = Object.getOwnPropertyNames(target)
    var enum_only = Object.keys(target)
    var nonenum_only = enum_and_noenum.filter(function(key){
      var indexInEnum = enum_only.indexOf(key)
      if(indexInEnum == -1) {
        return true
      }else {
        return false
      }
    })
    console.log(nonenum_only)

转自:https://www.cnblogs.com/kunmomo/p/12005794.html

猜你喜欢

转载自blog.csdn.net/u012687612/article/details/112790229