在if语句中检查“undefined”时出现“undefined”错误

时间:2013-04-22 08:51:36

标签: javascript object

我正在检查Object(如关联数组)以查看是否有一部分数据可用,但我在{{1}中得到undefined错误我正在检查它是否为if的声明!

我有undefined这样:

Object

我也尝试使用var data = { 1: { 2: { 3: [ ["a","b"], ["c","d"], ], } } } ,例如double-quotes

这些是我已经尝试过的var data = { "1": { "2": { ...陈述。所有这些都失败了,if正在Firebug语句中生成TypeError: data[1][2][3] is undefined

if

我在jsfiddle.net上检查过它并且工作正常。我尝试了所有我能想到的东西,但是我仍然不知道为什么它在if (typeof data[1][2][3] == "undefined") { if (data[1][2][3] === undefined) { // when I have double quotes if (typeof data["1"]["2"]["3"] == "undefined") { if (data["1"]["2"]["3"] === undefined) { 语句中失败了。

更新

看看这个,天啊:

enter image description here

5 个答案:

答案 0 :(得分:2)

如果variable[1][2][3]未定义,则脚本无法检查variable[1][2][3][4]是否未定义。您应该检查树的整个深度是否未定义

if(1 in variable)
{
  if(2 in variable[1])
  {
     if(3 in variable[1][2])
     {
       if(typeof variable[1][2][3][4] === 'undefined'){
          // Do something
       }
     }
  }
}

答案 1 :(得分:1)

一些评论,也许解决方案介于两者之间:

也许你想使用负面版

if (typeof data[1][2][3] !== "undefined") {

因为您似乎在条件体中处理该数据,所以您要确保在if条件中实际? Atm,如果数据未定义,代码将被执行

您是否在代码中使用了这个对象,还是仅用于演示目的?因为如果您检查data[1][2][3]并且data[1][2]已经未定义,则尝试访问data[1][2][3]会引发错误,因为您尝试访问非现有对象的属性。

旁注:如果你有数字索引,那么使用数组而不是对象可能更合适吗?

答案 2 :(得分:1)

更仔细地看看你的输出:

if (typeof e.Bubbles["2013"]["3"]["24"]["layer_1"] === "undefined") {
> TypeError e.Bubbles[2013][3][24] is undefined

即,因为你的测试太深了,所以它已经过时了。 ["24"]属性不存在,因此您无法访问["layer_1"]属性。

答案 3 :(得分:1)

如果您事先不知道是否拥有进入要检查的元素所需的所有层次结构(例如,您正在检查e.Bubbles[2013][3][4]["layer_1"],但e.Bubbles[2013]不存在,你得到TypeError),考虑使用这样的错误捕获:

try {
    myData = e.Bubbles[2013][3][4]["layer_1"];
} catch (error) {
    myData = undefined;
    console.error("Couldn't get my data", error.name, error.message);
}

if (myData !== undefined) {
    // Do something with the data
}

以使代码的可读性降低为代价,你也可以这样做:

var _ref, _ref1, _ref2;
if ((_ref = e.Bubbles[2013]) != null ? (_ref1 = _ref[3]) != null ? (_ref2 = _ref1[4]) != null ? _ref2["layer_1"] : void 0 : void 0 : void 0) {
  // We know we have e.Bubbles[2013][3][4]["layer_1"] here
}

但我建议错误捕捉。

答案 4 :(得分:-1)

不要将其与未定义的......进行比较。

如果你想检查它是否定义,那么只需将它放入IF条件,如...

var data = {
    1: {
        2: {
            3: [
                ["a","b"],
                ["c","d"],
            ],
        }
    }
}

if(data[1][2][3])
{
    alert("defined");
}
else
{
    alert("not defined");
}