#76 属性闪烁


  • 0
    administrators

    完成一个 flikerProps 方法,接受一个对象作为参数。可以把该对象的不可遍历属性变成可遍历属性;把可遍历属性变成不可遍历属性。例如:

    const obj = {}
    const config1 = { enumerable: false, configurable: true }
    const config2 = { enumerable: true, configurable: true }
    
    Object.defineProperties(obj, {
      green: config1,
      red: config2,
      blue: config1,
      yellow: config2
    })
    
    console.log(Object.keys(obj)) // => ["red", "yellow"]
    flikerProps(obj) // 闪烁
    console.log(Object.keys(obj)) // => ["green", "blue"]
    flikerProps(obj) // 闪烁
    console.log(Object.keys(obj)) // => ["red", "yellow"]
    flikerProps(obj) // 闪烁
    console.log(Object.keys(obj)) // => ["green", "blue"]
    

    注意不要触碰到传入对象的 prototype。


  • 0

    Object.keys
    Object.getOwnPropertyNames
    

    get


  • 0

    @ScriptOJ 为什么这样子会报错呢:Error 你不能触碰对象的原型,例如使用 for...in 来遍历

    const flikerProps = (obj) => {
      Object.getOwnPropertyNames(obj).forEach((k)=>{
        Object.defineProperty(obj, k, {enumerable: !obj.propertyIsEnumerable(k)})
      })
    }
    

    表单验证工具 https://github.com/WLDragon/SMValidator


  • 1

    @WLDragon 因为propertyIsEnumerable是obj原型上的方法,有点小坑

    const flikerProps = (obj) => {
      const a = Object.getOwnPropertyNames(obj)
      const b = Object.keys(obj)
      for (let i = 0; i < a.length; i++) {
        Object.defineProperty(obj, a[i], {enumerable: b.indexOf(a[i]) === -1})
      }
    }
    

  • 0

    const flikerProps = (obj) => {
      for (let [k, v] of Object.getOwnPropertyNames(obj).entries()) {
        Object.defineProperty(obj, v, {
          enumerable: !Object.getOwnPropertyDescriptor(obj, v).enumerable
        }) 
      }
    }
    

  • 0

    const flikerProps = obj => {
      const keys = Object.getOwnPropertyNames(obj)
    
      for (let key of keys) {
        const config = Object.getOwnPropertyDescriptor(obj, key)
    
        Object.defineProperty(obj, key, Object.assign({}, config, { enumerable: !config.enumerable }))
      }
    }
    
    // or
    
    const flikerProps = obj => {
      const keys = Object.getOwnPropertyNames(obj)
    
      const properties = Object.getOwnPropertyNames(obj).reduce((acc, x) => {
        const config = Object.getOwnPropertyDescriptor(obj, x)
    
        return {
          ...acc,
          [x]: { ...config, enumerable: !config.enumerable }
        }
      }, {})
    
      Object.defineProperties(obj, properties)
    }
    

  • 0

    const flikerProps = obj => {
      const desc = Object.getOwnPropertyDescriptors(obj)
      for(let key in desc) {
        Object.defineProperty(obj, key, {
          enumerable: desc[key].enumerable ? false : true
        })
      }
    }
    

  • 0

    const flikerProps = obj => Reflect.ownKeys(obj).map(v => {
      const {enumerable} = Object.getOwnPropertyDescriptor(obj, v)
      Object.defineProperty(obj, v, {
        enumerable: !enumerable
      })
    })
    

登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待