如何在不出现控制台错误的情况下检查 API 对象是否未定义?

How do you check if an API Object is undefined without getting a console error?

我正在使用 JSAJAX 从 Web-API(用于加密矿池)收集信息。几乎所有功能都可以完美运行,但是对于开发人员设置服务器的方式,当未使用某个值时,它可能是 empty,而不是 0。其他人确实有一个占位符值(我正在与开发人员讨论给所有内容一个占位符,但在那之前,我需要一些帮助)。

例如:

{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}},"auxiliary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}}}}

您可以看到在 body.primary.shares.shared 下它只是 [] 而不是零值。

这是脚本的一部分:

function avianDashboard(api, workerAPI) {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", api, true);
    xhr.onload = function () {
        if (this.status === 200) {
            obj = JSON.parse(this.responseText);
            if (typeof (obj.body.primary.shares.shared) === 'undefined') {
                document.getElementById('minerShares').innerHTML = 0;
            } else {
                document.getElementById('minerShares').innerHTML = obj.body.primary.shares.shared.valid;
            }

//Rest of the function works properly so I've omitted it for the sake of sanity

当我 运行 页面时, console.log 显示这个..

uncaught TypeError: Cannot read properties of undefined (reading 'shared') at XMLHttpRequest.xhr.onload (avian.php:784:61)

并指向这一行:

if (typeof (obj.body.primary.shares.shared) === 'undefined') {

我发现了很多应该有助于解决这个问题的东西(包括使用 typeof 因为我最初只是使用 <1null 作为我的条件检查器那也没用。

如有任何帮助,我们将不胜感激。

您可以使用 optional chaining 检查对象的属性是否存在:

if(obj?.body?.primary?.shares?.shared) {
  ...
}

查看更多info here.