【问题标题】:Variable is used before being assigned using hasOwnProperty在使用 hasOwnProperty 分配之前使用变量
【发布时间】:2021-06-04 02:29:59
【问题描述】:

在这里继续我从 JavaScript 到 TypeScript 的过渡过程中的冒险......再一次,它是以前运行良好但现在不行的代码。我搜索了替代方法或其他方法来编写它,但我似乎找不到它们。

一段代码:

 class secondCommand extends Commands {
    async command() {
       let [ result ] = await sql.promise().query(`SELECT * FROM database WHERE pending = "TRUE"`)
       let userId = result.map(x => x.user_id)
       let login = result.map(x => x.login)
       for (var userIdKey in userId) userId.hasOwnProperty(userIdKey)
       for (var loginKey in login) login.hasOwnProperty(loginKey)
       let [ [ result ] ] = await sql.promise().query(`SELECT birth FROM dates WHERE "login" = "${login[loginKey]}" ORDER BY date DESC LIMIT 1`)
       let date = getDateDiff(result)
       ///// rest of code
    }
}

以前有人遇到过这个问题吗?如果是这样,你是如何解决这个问题的?非常感谢

【问题讨论】:

  • 错误信息到底是什么?此外,hasOwnProperty 你正在做的检查什么也没做,因为结果没有被使用
  • Variable 'loginKey' is used before being assigned. ts(2454) 编辑:它也表示我稍后使用的userIdKey
  • login 和 userId 是一个数组,它没有 hasOwnProperty。而且你没有在两个 for 循环上做任何事情
  • 我遇到了您使用未定义变量 loginKey 查询的问题
  • 您说该变量未定义让我想到在 for 循环之前声明它,它现在可以工作了!请看下面我的回答

标签: typescript


【解决方案1】:

这样做

login.forEach((item) => {
       let [ [ result ] ] = await sql.promise().query(`SELECT birth FROM dates WHERE "login" = "${item}" ORDER BY date DESC LIMIT 1`)
})

【讨论】:

    【解决方案2】:

    问题很简单...这是解决方法

        let userIdKey
        let loginKey
        for (userIdKey in userId) userId.hasOwnProperty(userIdKey)
        for (loginKey in login) login.hasOwnProperty(loginKey)
    

    感谢codingwith3dv!

    【讨论】:

    • 这只会给出数组中的最后一个索引
    猜你喜欢
    • 2019-11-06
    • 2021-08-16
    • 2021-12-29
    • 1970-01-01
    • 2017-12-03
    • 2019-01-19
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多