访问javascript数组元素时出错,尽管有检查

时间:2017-09-16 22:55:07

标签: javascript arrays javascript-objects

我正在使用我的javascript代码

if(
  typeof player['stats'] != undefined &&
  typeof player['stats']['guild'] != undefined &&
  typeof player['stats']['guild']['master'] != undefined &&
  typeof player['stats']['guild']['master']['since'] != undefined
)

然而我收到错误:

Cannot read property 'since' of null

我已经坚持了一段时间。任何javascript专家都可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

typeof返回字符串,因此请与" undefined"

进行比较
if(
  typeof player['stats'] != "undefined" &&
  typeof player['stats']['guild'] != "undefined" &&
  typeof player['stats']['guild']['master'] != "undefined" &&
  player['stats']['guild']['master'] != null &&
  typeof player['stats']['guild']['master']['since'] != "undefined"
)

答案 1 :(得分:1)

只需检查值是否真实:

A = A{1}

答案 2 :(得分:0)

您可以编写一个相当简单的对象getter函数,您可以传递该对象,然后使用点分隔键来查找如下所示的值:

function getObj(obj, key) {
  return key.split(".").reduce((acc, cur) => {
    if (acc !== undefined) {
      return acc[cur];
    }
    return acc;
  }, obj);
}

然后,您可以获取所需的值,看看它是否未定义:

const player = {
  stats: {
    guild: {
      master: {
        since: '2004'
      }
    }
  }
};

const since = getObj(player, 'stats.guild.master.since');
if (since) {
  // do some code
}

这是一个方便的实用程序函数,可以在任何对象上使用,使你的if语句更漂亮。

答案 3 :(得分:0)

您还可以使用临时变量避免多次查找:



player = { stats: { guild: { master: null } } }

if ((temp = player.stats) && 
    (temp = temp.guild)   && 
    (temp = temp.master)  && 
    (temp = temp.since) !== undefined)        
    console.log(true , temp)
else
    console.log(false, temp)


player.stats.guild.master = { since: 'today' }

if ((temp = player.stats) && 
    (temp = temp.guild)   && 
    (temp = temp.master)  && 
    (temp = temp.since) !== undefined)        
    console.log(true , temp)
else
    console.log(false, temp)