【问题标题】:how to check if a nested object property is undefined in Javascript?如何检查嵌套对象属性是否在 Javascript 中未定义?
【发布时间】:2013-01-22 18:01:58
【问题描述】:

我有一个 Javascript 对象,如果 postsome 未定义,我正在努力检查循环。

这是我的对象:

var indices = [{
    "indexAB": [{
        "postsome": [
            "keyword_abc",
            "keyword_def"
         ]
       }]
    },{
    "indexA": [{
        "postsome": [
            "keyword_abc"
        ]
      }]
    }
 ]

问题是,我不能直接引用indexA,indexABpostsome。一切都会变数。这就是我正在尝试的:

// passed parameter
var doc._id = "postsome";

// mapping priv
// "indices": [
//    {"name":"indexA","fields":["findMeA"]},
//    {"name":"indexAB", "fields":["findMeA","findMeB"]}
//    ],

for (var i = 0, l = indices.length; i < l; i += 1) {

  var index = priv.indices[i];
      index_name = index["name"]; // indexAB or indexA

  // I can't reference indexAB directly 
  if ( indices[i].indexAB !== undefined && indices[i].indexAB.length  >  0 )          {
      console.log( indices[i].indexAB );
      console.log( indices[i].indexAB[0][doc._id] );

      if (indices[i].indexAB[0][doc._id] !== undefined) {
        console.log("gotcha");
        trigger = true;
      }
    }
}

所以当我使用indexAB 硬编码时,它可以工作,但我需要遍历这些值('indexA' 和 'indexAB' instea)。

问题:
有没有办法用变量替换.indexAB[0]?如果有,怎么做?

谢谢!

【问题讨论】:

  • var prop = 'indexAB'; indices[i][prop]... 这个问题已经被问过很多次了。
  • 让我试试。我不敢相信这很容易......

标签: javascript jquery object properties undefined


【解决方案1】:

只需使用括号符号,与 [doc._id] 完全相同。

if (indices[i][index_name] !== undefined && indices[i][index_name].length > 0)

括号符号和点符号是可以互换的,所以这两行是等价的:

indices.foo
indices["foo"]

但是,如果您需要使用变量,indices.varName 将转换为 indices["varName"],因此您必须使用括号表示法以确保它使用变量值而不是变量名作为字符串。

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2022-06-30
    • 2016-08-29
    • 1970-01-01
    • 2011-08-15
    • 2015-06-04
    • 1970-01-01
    • 2017-08-02
    • 2010-09-13
    相关资源
    最近更新 更多