【问题标题】:understanding local variables, closures and iterators了解局部变量、闭包和迭代器
【发布时间】:2020-11-22 11:49:31
【问题描述】:

我有一个如下所示的代码块,它是一个同步功能。 我想在reply收集物品信息。

但是,即使我有项目,回复也总是作为空数组返回。 当我签入调试器时,信息将reply 显示为闭包变量,而不是local。 我想知道这里的吊装是否有什么我不明白的地方?

  invStatus() {
    let reply: string[] = []
    Logger.log('player.status.items:', this.items)
    if (!this.items.length) {
      reply.push('nothing')
    } else this.items.map(item => {
      Logger.log('item', item)
      reply.push[`- ${item.name}`]
    })
    Logger.log('player.status.reply:', reply)
    return reply
  }

嗯,这也是打字稿,我想知道转译器的行为是否有细微的不同?

我可能应该在这里使用.forEach,因为我没有捕获地图的返回或转换事物,但我知道它具有相同的迭代器行为。唯一的另一件事是使用更可靠的for x of,但我想了解这里的问题!

【问题讨论】:

    标签: javascript typescript asynchronous iterator closures


    【解决方案1】:

    我认为你犯了语法错误。

    观察这一行:

    reply.push[`- ${item.name}`]
    

    这里,您使用的是方括号,而不是parantheses

    更正后的代码是,

    reply.push(`- ${item.name}`)
    

    我知道 javascript 但不知道 typescript,但我相信这一定是问题的原因。

    【讨论】:

    • 你是对的!我使用打字稿来帮助防止我犯这样的白痴错误。谢谢!
    猜你喜欢
    • 2012-12-24
    • 2011-01-21
    • 2020-03-30
    • 2016-06-04
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2021-01-29
    • 2018-12-24
    相关资源
    最近更新 更多