javascript - 无法解构函数生成器中的对象

标签 javascript ecmascript-6 generator

我想在对象为空时使用默认值解构先前 yield 的结果。但是我得到了一个无法读取未定义的属性 'xxx',这意味着我尝试解构变量 theObject 的地方是未定义的,但为什么呢?

const DEFAULT_POSITION = {x: 20, y: 20}
const myObject = {}

function* myGenerator(i) {
  const theObject = yield myObject;
  const { posX = DEFAULT_POSITION.x, posY = DEFAULT_POSITION.y, scale = 1 } = theObject

  yield {posX, posY, scale}
}

第一个 yield 按预期返回一个空对象,但是当我再次运行生成器时,我收到错误消息,即无法读取对象破坏中的第一项 (posX),因为theObject 未定义。

最佳答案

问题是您yield myObject给调用者yield的结果是从调用者读取的em> 通过 next(/* 这个“未定义”参数被传递到你的生成器函数 */) 调用。所以 theObjectundefined 因为你没有按预期使用生成器。

When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator

Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function *

这不是很直观,生成器函数很奇怪。

以下是可行的,但据我所知可能不是您想要的

const DEFAULT_POSITION = {x: 20, y: 20}
const myObject = {}

function* myGenerator(i) {
  const theObject = yield
  const { posX = DEFAULT_POSITION.x, posY = DEFAULT_POSITION.y, scale = 1 } = theObject

  yield {posX, posY, scale}
}
const it = myGenerator()
console.log(it.next()) // -> {value: undefined, done: false}
console.log(it.next(myObject)) // -> {value: { posX: 20, posY: 20, scale: 1 }, done: false}

关于javascript - 无法解构函数生成器中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60543593/

相关文章:

javascript - 如何使用 Jquery 中的 next() 函数将类添加到链接?

javascript - 使用ajax()时的全局变量

vb.net - 如何编写条码生成器?

终端中的 Python 素数生成器

python - 为什么 yield 需要 python 生成器?

javascript - 如何在 CSS 中检查条件?

javascript - 附加选项列表但删除以前的选项

javascript - 根据 Javascript 中不同的搜索属性值数组匹配数组中的一组对象

javascript - JS indexOf 对象数组和 splice() 没有删除正确的对象

javascript - 从 Map 获取与所使用的原始键相同但不是引用的值