Skip to content

Latest commit

 

History

History
50 lines (40 loc) · 1.56 KB

#76-属性闪烁.md

File metadata and controls

50 lines (40 loc) · 1.56 KB

题目描述:

完成一个 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。


思路:

如何遍历对象的property 属性,并且更改property属性。 Object.getOwnPropertyNames() Object.keys() Object.defineProperty()


参考答案:

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})
  }
}