const [a,b] = {a: 1,b: 2} 如何正确得出a=1;b=2?

186 阅读1分钟

这道题你会吗?

const [a,b] = {a: 1,b: 2}
console.log(a,b)
// TypeError: {(intermediate value)(intermediate value)} is not iterable

expect result is 1, 2
# 如何做到正确(解构)打印 a和b ?

结构的本质

const arr = [1, 2, 3]
const iter = arr[Symbol.iterator]()
const a = iter.next().value
const b = iter.next().value
const c = iter.next().value

console.log(a,b,c)  // 1, 2 ,3

结果1

const [a, b] = {
  a: 1,
  b: 2,
  [Symbol.iterator]() {
    const arr = Object.values(this)
    const iter = arr[Symbol.iterator]()
    return iter
  }
}
console.log(arr)

结果2

// 放在原型上
Object.prototype[Symbol.iterator] = function (){
  return Object.values(this)[Symbol.iterator]()
}