繁体   English   中英

无法读取未定义的属性

[英]cannot read the property of undefined

我在节点JS中编码服务器端应用程序,并且在MySQL中使用数据库。

我收到“ TypeError:无法读取未定义的属性“已激活””

当我在MySQL终端中手动执行请求时,我应该说“空集”。

当我尝试在我输入的代码中使用无效的discord_key时,它返回错误,但我希望它仅返回错误警报,以便我可以捕获并使用该信息。

function checkKey(key) {
    var activated = "";
    var sqlcheck = "SELECT activated from authentification where discord_ key = ?";
    console.log("in function");
    DB.query(sqlcheck, [key], function (err, result) {
        if (err) throw (err);
        activated = result[0].activated;
    });
    if (!activated) {
        console.log("null");
        return ("NULL");
    } else {
        console.log("used");
        return ("used");
    }
}

我应该得到:

该请求发送了一个空集,因此密钥不存在。

谢谢您的帮助!

如果没有结果,您可以这样写:

if (err) throw (err);
activated = result.length ? result[0].activated : false;

如果没有结果,它将返回false。

错误

错误提示您正在使用的变量未定义。 它告诉您这是因为您尝试从未定义的变量读取属性。

您提到的result是一个空数组。 这意味着您尝试访问的任何索引都将返回undefined 例如:

let result = []
console.log(result[0] === undefined) // prints true

在javascript中,如果尝试访问undefined属性,则会收到错误消息。 继续我们的示例:

result[0].activated // Throws error: Cannot read property 'activated' of undefined.

由于没有保证result[0]具有值,因此在访问其属性之前,应确保它没有undefined 如@NipunChawla所示,一种方法是检查数组的长度(即至少一个值):

if (result.length) { // Does result have values?
  activated = result[0].activated
} else {
  activated = false
}

更好的是,如果您知道仅使用result[0] ,请检查是否直接定义了它:

if (result[0]) { // Does result[0] have a value?
  activated = result[0].activated
} else {
  activated = false
}

您仍然有可能result[0].activated不存在。 表示activatedundefined

if (result[0] && result[0].activated) { // ... and does the first value
                                        // contain the property activated?
  activated = result[0].activated
} else {
  activated = false
}

所以现在在一起:

DB.query(sqlcheck, [key], function (err, result) {
  if (err) throw (err);
  if (result[0] && result[0].activated) {
    activated = result[0].activated
  } else {
    activated = false
  }
})

异步回调

要解决!activated第二if语句始终是true ,你应该考虑的回调是如何工作的。 基本上, DB.query会关闭并执行其操作。 完成后,它将执行您作为回调提供的功能。 执行顺序如下所示:

  1. 调用DB.query向数据库发送请求
  2. 继续执行脚本。 即检查if (!activated) { ...
  3. DB.query现在已经完成并调用您的回调,并分配了activated = result[0].activated function(err, result)

您可以通过以下方法解决此问题:

function checkKey(key) {
  var activated = "";
  var sqlcheck = "SELECT activated from authentification where discord_ key = ?";
  console.log("in function");
  DB.query(sqlcheck, [key], function (err, result) {
    if (err) throw (err);
    if (result[0] && result[0].activated) {
      activated = result[0].activated
    } else {
      activated = false
    }

    doSomethingWithResult(activated)
  });
}

function doStuffWithResult(activated) {
  if (!activated) {
    console.log("null");
    // Do your !activated stuff
  } else {
    console.log("used");
    // Do your activated stuff
  }
}

有关更多信息,请参见此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM