【问题标题】:JavaScript multidimensional-array check if typeof is 'undefined'JavaScript 多维数组检查 typeof 是否为“未定义”
【发布时间】:2021-04-07 20:02:41
【问题描述】:

如果你创建一个多维数组:

var ThisArray = [];
ThisArray["a"] = [];
ThisArray["a"]["b"] = [];
ThisArray["a"]["b"]["c"] = "This is a string.";

如何检查 ThisArray["a"]["w"]["c"] 例如是否已定义。现在我正在这样做:

if (typeof ThisArray !== 'undefined') {
    if (typeof ThisArray["a"] !== 'undefined') {
        if (typeof ThisArray["a"]["w"] !== 'undefined') {
            if (typeof ThisArray["a"]["w"]["c"] !== 'undefined') {

                // ThisArray["a"]["w"]["c"] is defined!

            }
        }
    }
}

我怎样才能做得更好、更干净?

【问题讨论】:

  • 数组应该有数字索引,而不是字符串。你的意思是使用对象{}

标签: javascript arrays multidimensional-array


【解决方案1】:

使用optional chaining:

if (typeof ThisArray?.["a"]?.["w"]?.["c"] !== 'undefined') {
   // ThisArray["a"]["w"]["c"] is defined!
}

正如 cmets 中所述,这是一个相对较新的语言功能,旧浏览器不支持。见Browser Compatibility

【讨论】:

【解决方案2】:

您可以使用可选链接。 当引用或函数可能未定义或为空时,可选的链接运算符支持通过连接对象访问值的简单方法,从而保护您免受空/未定义对象的空异常。

var ThisArray = [];
ThisArray["a"] = [];
ThisArray["a"]["b"] = [];
ThisArray["a"]["b"]["c"] = "This is a string.";

console.log(ThisArray.a.b.c?.d?.e);

【讨论】:

    【解决方案3】:

    这是使用可选链接的理想场所!

    你可以这样做:

    if (typeof ThisArray.a?.b?.c !== 'undefined') {
      console.log(`ThisArray["a"]["b"]["c"] is defined!`);
    }
    

    这是一个完整的演示:

    var ThisArray = [];
    ThisArray["a"] = [];
    ThisArray["a"]["b"] = [];
    ThisArray["a"]["b"]["c"] = "This is a string.";
    
    if (typeof ThisArray.a?.b?.c !== 'undefined') {
      console.log(`ThisArray["a"]["b"]["c"] is defined!`);
      console.log(`ThisArray.a.w.c === "${ThisArray.a.b.c}"`)
    } else {
      console.log(`ThisArray["a"]["b"]["c"] is NOT defined!`);
    }

    【讨论】:

      【解决方案4】:

      尝试捕捉

      var thirdDimensionValue = null;
      try{
      thirdDimensionValue = ThisArray["a"]["b"]["c"]
      }
      catch{
      thirdDimensionValue = null
      }
      if(thirdDimensionValue){
      console.log("value exist")
      }
      else{
      console.log("No value exist in the property")
      }

      【讨论】:

        猜你喜欢
        • 2012-07-05
        • 2013-06-22
        • 2017-05-29
        • 1970-01-01
        • 2010-09-26
        • 2010-09-13
        • 2023-03-26
        • 2015-09-27
        • 2013-08-26
        相关资源
        最近更新 更多