Array Argument Desctructuring会引发意外错误

时间:2016-11-08 01:38:07

标签: javascript arrays node.js

正在尝试节点6.9.0并编写了以下示例:

'use strict'

function hello (opts) {
  let [ firstName, lastName, age ] = opts
  console.log(`Hello ${firstName} ${lastName}. Glad you're feeling ${age}`)
}
hello({})

我得到的结果是:

/Users/hiphipjorge/runnable/blog-posts/november-2016/index.js:6
  let [ firstName, lastName, age ] = opts
                                     ^

TypeError: undefined is not a function
    at hello (/Users/hiphipjorge/runnable/blog-posts/november-2016/index.js:6:38)
    at Object.<anonymous> (/Users/hiphipjorge/runnable/blog-posts/november-2016/index.js:9:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)

错误所指的undefined函数是什么?我可以为任何对象提供接口数组以进行数组解构吗?

1 个答案:

答案 0 :(得分:0)

您需要为对象提供迭代器生成器(*[Symbol.iterator]())才能使其正常工作。

'use strict'

class KindaSortaLikeAnArray {
  *[Symbol.iterator](){
    yield 1;
    yield 2;
    yield 3;
  }
}

function hello (opts) {
  let [ firstName, lastName, age ] = opts
  console.log(`Hello ${firstName} ${lastName}. Glad you're feeling ${age}`)
}
hello(new KindaSortaLikeAnArray())

这个迭代器可以通过以下方式遍历对象的键:

'use strict'

var obj = {
  hello: 'world',
  wow: 'great',
  a: 'b'
}
obj[Symbol.iterator] = function*(){
  let keys = Object.keys(this)
  for (let key of keys) {
    yield this[key]
  }
}

function hello (opts) {
  let [ firstName, lastName, age ] = opts
  console.log(`Hello ${firstName} ${lastName}. Glad you're feeling ${age}`)
}
hello(obj)